Search code examples
c#xmllinqnamespacesxmldocument

Selecting Particular Node List in XML


<Report xmlns="Microsoft.SystemCenter.DataWarehouse.Report.Alert" xmlns:p1="w3.org/2001/XMLSchema-instance"; Name="Microsoft.SystemCenter.DataWarehouse.Report.Alert" p1:schemaLocation="Microsoft.SystemCenter.DataWarehou?Schema=True">
 <Title>Alert Report</Title>
 <Created>6/27/2013 9:32 PM</Created>
 <StartDate>6/1/2013 9:29 PM</StartDate>
 <EndDate>6/27/2013 9:29 PM</EndDate>
 <TimeZone>(UTC)</TimeZone>
 <Severity>Warning, Critical</Severity>
 <Priority>Low, Medium, High</Priority>
<AlertTable>
    <Alerts>
        <Alert>
               <AlertName></AlertName>
               <Priority></Priority>
        </Alert>
    </Alerts>
</AlertTable>
</Report>

So I'm trying to pull down the list of nodes that appear under Alerts child. So /Report/AlertTable/Alerts. I've done very similar before but in this format it is not working for some reason. Can someone point me out in the right direction?

  XmlDocument Log = new XmlDocument();
        Log.Load("test.xml");
        XmlNodeList myLog = Log.DocumentElement.SelectNodes("//Report/AlertTable/Alerts");

        foreach (XmlNode alert in myLog)
        {
            Console.Write("HERE");
            Console.WriteLine(alert.SelectNodes("AlertName").ToString());
            Console.WriteLine(alert.SelectNodes("Priority").ToString());
            Console.Read();
        }

EDIT: One of the responses had me try to use a bunch of namespace with p1 but had no such luck.

EDIT: Did not work either:

    var name = new XmlNamespaceManager(log.NameTable);
    name.AddNamespace("Report", "http://www.w3.org/2001/XMLSchema-instance");
    XmlNodeList xml = log.SelectNodes("//Report:Alerts", name);

Solution

  • Figured this sucker out. It had to do with the namespace of "Microsoft.SystemCenter.DataWarehouse.Report.Alert". Changing this to anything but that won't read the XML properly.

            XmlDocument log = new XmlDocument();
            log.Load(@"C:\Users\barranca\Desktop\test.xml");
           // XmlNodeList xml = log.SelectNodes("//ns1:Alerts");
    
            var name = new XmlNamespaceManager(log.NameTable);
            name.AddNamespace("ns1", "Microsoft.SystemCenter.DataWarehouse.Report.Alert");
            XmlNodeList xml = log.SelectNodes("//ns1:Alert", name);
    
    
    
            foreach (XmlNode alert in xml)
            {
                Console.Write("HERE");
                XmlNode test = alert.SelectSingleNode("//ns1:AlertName",name);
                string testing = test.InnerText;
                Console.Write(testing);
            }