简体   繁体   English

XML - 如何使用名称空间前缀

[英]XML - how to use namespace prefixes

I have this XML at http://localhost/file.xml :我在http://localhost/file.xml有这个 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:我正在尝试从我的 c# 代码中读取此内容:

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"?我知道这是阅读 XML 时常见的新手问题,仍然无法解决我做错的事情,可能是命名空间“val”的问题?

You need to pass the namespace manager into the SelectNodes() method.您需要将命名空间管理器传递给 SelectNodes() 方法。

Edit: corrected code编辑:更正代码

XmlNodeList nodes = root.SelectNodes("/val:Root/SenSet/Entry", nsmgr);

Just change you Xpath to:只需将您的 Xpath 更改为:

XmlNodeList nodes1 = root.SelectNodes("/val:Root/SenSet/Entry",nsmgr);    

Or:要么:

XmlNodeList nodes = root.SelectNodes("SenSet/Entry");

Your xpath query string should be:您的 xpath 查询字符串应该是:

XmlNodeList nodes = root.SelectNodes("/val:Root/SenSet/Entry", nsmgr);

or more concisely,或者更简洁地说,

XmlNodeList nodes = root.SelectNodes("//SenSet/Entry", nsmgr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM