XML - how to use namespace prefixes

Posted by Asbie on Stack Overflow See other posts from Stack Overflow or by Asbie
Published on 2012-04-04T17:08:29Z Indexed on 2012/04/04 17:29 UTC
Read the original article Hit count: 261

Filed under:
|
|

I have this XML at http://localhost/file.xml:

<?xml version="1.0" encoding="utf-8"?>
<val:Root xmlns:val="http://www.hw-group.com/XMLSchema/ste/values.xsd">
<Agent>
<Version>2.0.3</Version>
<XmlVer>1.01</XmlVer>
<DeviceName>HWg-STE</DeviceName>
<Model>33</Model>
<vendor_id>0</vendor_id>
<MAC>00:0A:DA:01:DA:DA</MAC>
<IP>192.168.1.1</IP>
<MASK>255.255.255.0</MASK>
<sys_name>HWg-STE</sys_name>
<sys_location/>
<sys_contact>
HWg-STE:For more information try http://www.hw-group.com
</sys_contact>
</Agent>
<SenSet>
<Entry>
<ID>215</ID>
<Name>Home</Name>
<Units>C</Units>
<Value>27.7</Value>
<Min>10.0</Min>
<Max>40.0</Max>
<Hyst>0.0</Hyst>
<EmailSMS>1</EmailSMS>
<State>1</State>
</Entry>
</SenSet>
</val:Root>

I am trying to read this from my c# code:

static void Main(string[] args)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load("http://localhost/file.xml");
            XmlElement root = xmlDoc.DocumentElement;
            // Create an XmlNamespaceManager to resolve the default namespace.
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
            nsmgr.AddNamespace("val", "http://www.hw-group.com/XMLSchema/ste/values.xsd");

            XmlNodeList nodes = root.SelectNodes("/val:SenSet/val:Entry"); 
            foreach (XmlNode node in nodes)
            {
                string name = node["Name"].InnerText;
                string value = node["Value"].InnerText;

            Console.Write("name\t{0}\value\t{1}", name, value);
            }
            Console.ReadKey();

        }
    }

Problem is that the node is empty. I understand this is a common newbie problem when reading XML, still not able to solve what I am doing wrong, probably something with the Namespace "val" ?

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml