I’m trying to use XmlDocument() to read an XML file node by node an output each element.
After much trial-and-error, I determined that having an xmlns attribute on my node causes no nodes to be returned from SelectNodes() call. Not sure why.
Since I can’t change the output format and don’t have access to the actual namespace, what are my options to get around this issue?
In addition, I have some elements that have subnodes. How do I access these while looping through the XML file? I.E., I need to decrypt the CipherValue elements, but not sure how to access this node anyway?
Sample below:
doc.Load(@"test.xml");
XmlNodeList logEntryNodeList = doc.SelectNodes("/Logs/LogEntry");
Console.WriteLine("Nodes = {0}", logEntryNodeList.Count);
foreach (XmlNode xn in logEntryNodeList)
{
string dateTime = xn["DateTime"].InnerText;
string sequence = xn["Sequence"].InnerText;
string appId = xn["AppID"].InnerText;
Console.WriteLine("{0} {1} {2}", dateTime, sequence, appId);
}
Sample XML looks like this:
<Logs>
<LogEntry Version="1.5" PackageVersion="10.10.0.10" xmlns="http://private.com">
<DateTime>2013-02-04T14:05:42.912349-06:00</DateTime>
<Sequence>5058</Sequence>
<AppID>TEST123</AppID>
<StatusDesc>
<EncryptedData>
<CipherData xmlns="http://www.w3.org/2001/04/xmlenc#">
<CipherValue>---ENCRYPTED DATA BASE64---</CipherValue>
</CipherData>
</EncryptedData>
</StatusDesc>
<Severity>Detail</Severity>
</LogEntry>
<LogEntry Version="1.5" PackageVersion="10.10.0.10" xmlns="http://private.com">
<DateTime>2013-02-04T14:05:42.912350-06:00</DateTime>
<Sequence>5059</Sequence>
<AppID>TEST123</AppID>
<StatusDesc>
<EncryptedData>
<CipherData xmlns="http://www.w3.org/2001/04/xmlenc#">
<CipherValue>---ENCRYPTED DATA BASE64---</CipherValue>
</CipherData>
</EncryptedData>
</StatusDesc>
<Severity>Detail</Severity>
</LogEntry>
</Logs>
You can use Linq to Xml (as Jon stated). Here is code which parses your xml file with respect to namespaces. Result is a strongly typed sequence of anonymous objects (i.e. Date property has type of DateTime, Sequence is integer, and AppID is a string):