Iterate XML Document and Add Attirbute?

X

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.
 
V

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.
 
X

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top