Dan Orlovsky
Dan Orlovsky

Reputation: 1093

Getting child nodes in XML with custom Namespace

I have a rather large XML file from a computer diagnostics session, and my goal is to grab the test results data and pump it into a PDF for the customer. I've very little experience with XML and this is turning out to be a huge problem.

Here is a sample of the Document:

<pcd:DiagLog xmlns="http://www.pc-doctor.com/2004/8/diagLogger"
             xmlns:pcd="http://www.pc-doctor.com/2004/8/diagLogger"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.pc-doctor.com/2004/8/diagLogger 
             http://www.pc-doctor.com/2004/8/diagLogger/diagLogger.xsd">
    <Application>
        <version>6.0.6818.10</version>
        <Start>
            <Time hour="04" minute="14" second="01" millisecond="34" month="10" day="15" year="2016" utcOffset="-480">2016-10-15T04:14:01.034-08:00</Time>
        </Start>
        <OS>Windows 10 Service Pack 0 PE x86 32-bit</OS>
    </Application>
       .......
    <DiagInfo>
      ....
        <TestResult EnglishResult="PASS">
                ....
        </TestResult>
    </DiagInfo>

There are thousands of lines between </Application> and <DiagInfo>, but I'm only concerned with the information found in <DiagInfo> and <TestResult>.

I thought I could grab the Nodes by simply:

    XmlDocument doc = new XmlDocument();
    doc.Load(xmlFilePath);
    XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
    manager.AddNamespace("pcd", "http://www.pc-doctor.com/2004/8/diagLogger");
    XmlNodeList xnList = doc.SelectNodes("/pcd:DiagLog/DiagInfo", manager);

But this is returning an empty list. When I refer to Namespace Manager or XsltContext needed, it appears I'm doing it right, but I don't think I'm understanding adding a namespace correctly. When I change the Root Element to just: <Diagnostics></Diagnostics> instead of the <pcd:DiagLog>, and try: doc.SelectNodes("/Diagnostics/DiagInfo", manager); my nodes list is populated.

Can anyone see where I'm screwing up the Namespace?

Upvotes: 0

Views: 1686

Answers (1)

Tomalak
Tomalak

Reputation: 338416

You need to use the namespace prefix for all nodes in that namespace.

This is incorrect: /pcd:DiagLog/DiagInfo.

This is correct: /pcd:DiagLog/pcd:DiagInfo.

Upvotes: 1

Related Questions