I have an application that is on .net 2.0 and I am having some difficult with it as I am more use to linq.
The xml file look like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<updates>
<files>
<file url="files/filename.ext" checksum="06B9EEA618EEFF53D0E9B97C33C4D3DE3492E086" folder="bin" system="0" size="40448" />
<file url="files/filename.ext" checksum="CA8078D1FDCBD589D3769D293014154B8854D6A9" folder="" system="0" size="216" />
<file url="files/filename.ext" checksum="CA8078D1FDCBD589D3769D293014154B8854D6A9" folder="" system="0" size="216" />
</files>
</updates>
The file is downloaded and readed on the fly:
XmlDocument readXML = new XmlDocument();
readXML.LoadXml(xmlData);
Initially i was thinking it would go with something like this:
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//files");
foreach (XmlNode node in nodes)
{
... im reading it ...
}
But before reading them I need to know how many they are to use on my progress bar and I am also clueless on how to grab the attribute of the file element in this case.
- How could I count how many “file”
ELEMENTS I have (count them before entering the foreach ofc) and read their
attributes ?
I need the count because it will be used to update the progress bar.
Overall it is not reading my xml very well.
Use the
XmlNodeList.Countproperty. Code example below.Here’s some tips on reading Xml with the older Xml library.
First, XPath is your friend. It lets you query elements pretty quickly, in a way that is (very) vaguely similar to Linq. In this case, you should change your XPath to get the list of child “file” elements, rather than the parent “files” element.
Becomes
The
//ElementNamesearches recursively for all elements with that name. XPath is pretty cool, and you should read up on a bit. Here are some links:Once you have those elements, you can use the
XmlElement.Attributesproperty, coupled with theXmlAttribute.Valueproperty (file.Attributes["url"].Value).Or you can use the
GetAttributemethod.Click this link to the documentation on
XmlElementfor more info. Remember to switch the .Net Framework version to 2.0 on that page.For how to convert your checksum into a byte array, see this question:
How can I convert a hex string to a byte array?