Home All Groups Group Topic Archive Search About

Iterate XML Document and Add Attirbute?

Author
2 Nov 2006 4:28 PM
xeroxero
I have an XML document with this as a sample fragment:

<?xml version="1.0" encoding="utf-16"?>
<directory path="c:\\test\\directory">
<file name="fileA.doc" />
<file name="fileB.txt" />
</directory>

I would like to iterate over the document, find any element that is
named 'file', and add an attribute 'size' if it doesn't already exist.
Can an XPathNavigator be used for that purpose, and if so how? I am
not sure about which tool to use, since it seems like I'll modify the
collection while it's in-use.

Thanks.

Author
2 Nov 2006 7:57 PM
Vadym Stetsyak
Hello, xeroxero!

You can use XML DOM model here and XPath.

So, the code can look like this:
XmlDocument xmlDoc= new XmlDocument();
xmlDoc.Load(xml);

XmlNodeList files = xmlDoc.SelectNodes("directory/file");
foreach(XmlNode file in files)
{
    //create attribute 'size' if it doesn't exist
}

You wrote  on Thu, 02 Nov 2006 11:28:04 -0500:

x> I have an XML document with this as a sample fragment:

x> <?xml version="1.0" encoding="utf-16"?>
x> <directory path="c:\\test\\directory">
x> <file name="fileA.doc" />
x> <file name="fileB.txt" />
x> </directory>

x> I would like to iterate over the document, find any element that is
x> named 'file', and add an attribute 'size' if it doesn't already
x> exist.
x> Can an XPathNavigator be used for that purpose, and if so how? I am
x> not sure about which tool to use, since it seems like I'll modify the
x> collection while it's in-use.

x> Thanks.

--
With best regards, Vadym Stetsyak.
Blog: http://vadmyst.blogspot.com
Author
3 Nov 2006 8:30 PM
xeroxero
Thanks, but that won't exactly do it. Sometimes, <directory> elements
can be in another directory. That's why I thought I need to use an
XPathNavigator.

What can I do?

Thanks.



Show quote
On Thu, 2 Nov 2006 21:57:34 +0200, "Vadym Stetsyak" <vady***@ukr.net>
wrote:

>Hello, xeroxero!
>
>You can use XML DOM model here and XPath.
>
>So, the code can look like this:
>XmlDocument xmlDoc= new XmlDocument();
>xmlDoc.Load(xml);
>
>XmlNodeList files = xmlDoc.SelectNodes("directory/file");
>foreach(XmlNode file in files)
>{
>    //create attribute 'size' if it doesn't exist
>}
>
>You wrote  on Thu, 02 Nov 2006 11:28:04 -0500:
>
> x> I have an XML document with this as a sample fragment:
>
>x> <?xml version="1.0" encoding="utf-16"?>
>x> <directory path="c:\\test\\directory">
>x> <file name="fileA.doc" />
>x> <file name="fileB.txt" />
>x> </directory>
>
>x> I would like to iterate over the document, find any element that is
>x> named 'file', and add an attribute 'size' if it doesn't already
>x> exist.
>x> Can an XPathNavigator be used for that purpose, and if so how? I am
>x> not sure about which tool to use, since it seems like I'll modify the
>x> collection while it's in-use.
>
>x> Thanks.

AddThis Social Bookmark Button