Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / XML / January 2008

Tip: Looking for answers? Try searching our database.

Editting an XML file

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
David - 17 Jan 2008 14:04 GMT
Hi all,

I am fairly new with XML.

I am using Compact Framework 1, targetting a pocketpc.

I have an xml file that due to its structure, cannot import into a dataset.
(Its structure is fine, just with nested tables causing probs). So, I am
reading through the XML file by hand using selectnodes, picking off the data
that I need.

The results are being displayed on screen, where they can be editted.

I need to save these results back to the XML (or a new copy if required) but
have no idea as to how to approach it.

Any pointers, links or code samples to achieve my goal would be very much
appreciated.

Signature

Best regards,
Dave Colliver.
http://www.AshfieldFOCUS.com
~~
http://www.FOCUSPortals.com - Local franchises available

Martin Honnen - 17 Jan 2008 14:23 GMT
> I am fairly new with XML.
>
[quoted text clipped - 12 lines]
> Any pointers, links or code samples to achieve my goal would be very much
> appreciated.

According to my documentation System.Xml.XmlDocument is supported in the
.NET Compact Framework 1.0 so assuming you have an XmlElement node in
your document you can change its content using the InnerText property
  XmlDocument doc = new XmlDocument();
  doc.Load("file.xml");
  XmlNode foo = doc.SelectSingleNode("root/foo");
  if (foo != null) {
    foo.InnerText = "new content";
  }
  // do further changes here
  // then save document back e.g.
  doc.Save("file2.xml");

That is just one example, if you want specific example then show us a
relevant sample of your XML and describe the changes you want to make,
then we are able to provide some code specific to your problem.

You might also want to read the MSDN documentation on the DOM
implementation in the .NET framework:
<URL:http://msdn2.microsoft.com/en-us/library/t058x2df(VS.80).aspx>

Signature

    Martin Honnen --- MVP XML
    http://JavaScript.FAQTs.com/

David - 17 Jan 2008 14:47 GMT
Thank you...

I know there are many parts of XML that do not work in CF, for example xpath
and xquery. The selectsinglenode is not directly supported, but I have found
an overriden xmldocument that has a selectsinglenode.

One of the probs I have is that of navigating rows (nodes with the same
name...). The sample xml will be too big here, so I have a layout sample...

  Part
       PartId (nodes under here)
       PartOperations
       PartImages
            PartImage
                 PartRegions
                      PartRegions
                           GridRef
                           Features
                                PartFeature
                                         (various nodes under PartFeature)
                      PartRegions
                           GridRef
                           Features
                                PartFeature

Also, under part feature are other nested nodes. Because of this structure,
I cannot really just select for example...

/Part/PartId/PartImages/PartImage/PartRegions/PartRegions/Features/PartFeature/<bit
I want to change>

in order to change a node. I somehow need to navigate through the nodes.

I guess (and I will give it a try) that I can go to

/Part/PartId/PartImages/PartImage/PartRegions/

then loop through all the (second level) PartRegions, replacing at will.
Does that sound like a plan?

Signature

Best regards,
Dave Colliver.
http://www.AshfieldFOCUS.com
~~
http://www.FOCUSPortals.com - Local franchises available

>
>> I am fairly new with XML.
[quoted text clipped - 34 lines]
> implementation in the .NET framework:
> <URL:http://msdn2.microsoft.com/en-us/library/t058x2df(VS.80).aspx>
Martin Honnen - 17 Jan 2008 15:39 GMT
> I know there are many parts of XML that do not work in CF, for example xpath
> and xquery. The selectsinglenode is not directly supported, but I have found
> an overriden xmldocument that has a selectsinglenode.

MS does not support XQuery at all in the .NET framework. XPath is
supported in both the normal .NET framework and the compact framework.

> One of the probs I have is that of navigating rows (nodes with the same
> name...). The sample xml will be too big here, so I have a layout sample...
[quoted text clipped - 29 lines]
> then loop through all the (second level) PartRegions, replacing at will.
> Does that sound like a plan?

Your structure is not clear, PartId, PartOperations, PartImages look
like siblings yet you use /Part/PartId/PartImages as if PartImages is a
child of PartId.
It is also not clear what exactly you want to change.
As for navigation, navigation in the DOM model can be done in various
ways, each node has a ChildNodes property, a FirstChild and LastChild
property, has NextSibling and PreviousSibling, and with DOM in the .NET
framework you have SelectNodes and SelectSingleNode not only on the
document node but on other nodes as well so you can use relative XPath
expression and those methods to access anything XPath allows you to
select. That way it is certainly possible to access certain nodes first
and then use further SelectSingleNode or SelectNodes on those nodes to
select children elements (*) or descendant elements (.//*).

Signature

    Martin Honnen --- MVP XML
    http://JavaScript.FAQTs.com/

David - 17 Jan 2008 16:39 GMT
Hi,

My mistake, PartID should not have been in my select statement. Sorry for
the confusion.

I am using .net CF1 and xpath is not in the framework. I don't think it is
in CF2 either.

Aside from that, your example led me onto a solution.

Due to the limitations of the XML stuff in compact framework, I am having to
loop through stuff (quite resource hungry I'm sure, but until I have more
experience, I can live with that.)

I have made my xdoc visible to the whole app, I open a doc inside my
form_load, looping through it to get at my data, then displaying it.

When ready, I click a save button. This gets the xdoc that is already open
and basically, all I do is to swap around read/write part of the statements
(I didn't know about this, your example told me...). I didn't know how to
save it either, again, your example showed me this.

I am happy now. Just got to do more rigourus testing now.

As an example, can you show me how to navigate to each PartFeature and to
get values out of say, 'FeatureID' under PartFeature, within the limitations
of the compact framework?

Thanks.
Signature

Best regards,
Dave Colliver.
http://www.AshfieldFOCUS.com
~~
http://www.FOCUSPortals.com - Local franchises available

>> I know there are many parts of XML that do not work in CF, for example
>> xpath and xquery. The selectsinglenode is not directly supported, but I
[quoted text clipped - 52 lines]
> and then use further SelectSingleNode or SelectNodes on those nodes to
> select children elements (*) or descendant elements (.//*).
Martin Honnen - 17 Jan 2008 17:05 GMT
> As an example, can you show me how to navigate to each PartFeature and to
> get values out of say, 'FeatureID' under PartFeature, within the limitations
> of the compact framework?

GetElementsByTagName should be available, as well as indexing child
elements by name so this example

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(@"<root>
  <foo>
    <bar>
      <item>value 1</item>
      <baz>value 2</baz>
    </bar>
    <bar>
      <item>value 3</item>
    </bar>
  </foo>
</root>");
            foreach (XmlElement bar in doc.GetElementsByTagName("bar"))
            {
                Console.WriteLine("item InnerText: \"{0}\".", bar["item"].InnerText);
            }

outputs "value 1" and "value 3".

If you have elements of the same name at different levels then
GetElementsByTagName is kind of dangerous however as it gives the
elements at all levels and it flattens the hierarchy and the nesting. In
that case you might need loop through ChildNodes of a node and check the
NodeType == XmlNodeType.Element to find child elements, if needed you
can add a check for the Name.

Signature

    Martin Honnen --- MVP XML
    http://JavaScript.FAQTs.com/

Martin Honnen - 17 Jan 2008 18:23 GMT
> If you have elements of the same name at different levels then
> GetElementsByTagName is kind of dangerous however as it gives the
> elements at all levels and it flattens the hierarchy and the nesting. In
> that case you might need loop through ChildNodes of a node and check the
> NodeType == XmlNodeType.Element to find child elements, if needed you
> can add a check for the Name.

Here is an example how you could build your own method to find child
elements of a certain name:

        static ArrayList GetChildElements (XmlNode node, string name)
        {
            ArrayList elements = new ArrayList();
            foreach (XmlNode child in node.ChildNodes)
            {
                if (child.NodeType == XmlNodeType.Element && child.Name == name)
                {
                    elements.Add(child);
                }
            }
            return elements;
        }

used like this:

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(@"<root>
  <foo>
    <child>
      <child>
        <bar></bar>
      </child>
      <item>value 1</item>
    </child>
    <whatever/>
    <child>
      <item>value 2</item>
    </child>
  </foo>
</root>");
            ArrayList childElements =
GetChildElements(doc.DocumentElement["foo"], "child");
            foreach (XmlNode node in childElements)
            {
                Console.WriteLine(node["item"].InnerText);
            }

Signature

    Martin Honnen --- MVP XML
    http://JavaScript.FAQTs.com/

David - 17 Jan 2008 21:08 GMT
Hi,

Thanks for these.

I did try GetElementByTagName but gave up on that, for exactly the problem
you outlined, as I have nested elements with the same name. (I am not
controlling the name). THe method you have outlined here is similar to what
I have written already (though I have done the loop inside the function
rather than calling a seperate function to do the loop).

I have another problem now and not sure what is causing it...

A whole segment of my XML is disappearing during my save. This is really odd
as I am not reading or writing any of this section.

Basically, I am loading the XML at start-up and putting it into an
XMLDocument that is globally accessed.
I am parsing the XML similar to what you have outlined below and building up
a datatable to be used in my app.
I then display the first record.
Even without doing anything to the XML itself, when I click my save button,
I am just saving the data in exactly the opposite way that I collect the
data from the XML file, yet a good chunk is disappearing that I am not even
touching. (How confused am I?)

Based on my previous tree, there are nodes and leafs between PartImage and
PartRegions (they are earlier siblings to PartRegions (the first level
PartRegions)). This area is absolutely critical to the functionality of the
desktop version of the app and I really don't understand why it is
disappearing.

I will try and do a debug, but I don't know where the problem will lie. Even
though you haven't seen the code yet, do you know of anything that I might
have overlooked that would cause this?

Signature

Best regards,
Dave Colliver.
http://www.AshfieldFOCUS.com
~~
http://www.FOCUSPortals.com - Local franchises available

>
>> If you have elements of the same name at different levels then
[quoted text clipped - 43 lines]
> Console.WriteLine(node["item"].InnerText);
> }
David - 17 Jan 2008 21:30 GMT
Further to my last...

It is disappearing as soon as I load the document, before I have done any
processing.

Basically, I have an overriden XmlDocument. I have put breakpoints all over
this class to ensure that nothing is being run during instantiation.

Then, I have

XDoc MyDoc = new XDoc;    // XDoc is the override name of XmlDocument. This
is outside of the functions.

in my startup function I have a file open dialog to select the file.

XDoc.Load(FileName);

I then go into my command window and type...

XDoc.InnerXML and I search for a unique word in the 'missing' text and sure
enough, that whole section is gone. I have also done a selectnode and it
does not exist.

Is there a known problem with XmlDocument?

Signature

Best regards,
Dave Colliver.
http://www.AshfieldFOCUS.com
~~
http://www.FOCUSPortals.com - Local franchises available

> Hi,
>
[quoted text clipped - 77 lines]
>> Console.WriteLine(node["item"].InnerText);
>> }
David - 17 Jan 2008 22:06 GMT
Sorry about all this...

I sorted it, though don't know why it is happening.

Basically, I am doing a selectNode to
/Part/PartImages/PartImage/PartRegions

Immediately after this line, I lose the data, which is really odd, so I have
come up one stage earlier and added an extra loop (this is both on the open
and save).

Works now. Was pulling my hair out with this.
Signature

Best regards,
Dave Colliver.
http://www.AshfieldFOCUS.com
~~
http://www.FOCUSPortals.com - Local franchises available

> Further to my last...
>
[quoted text clipped - 102 lines]
>>> Console.WriteLine(node["item"].InnerText);
>>> }

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.