簡體   English   中英

XML - 如何使用名稱空間前綴

[英]XML - how to use namespace prefixes

我在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>

我正在嘗試從我的 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();

        }
    }

問題是節點是空的。 我知道這是閱讀 XML 時常見的新手問題,仍然無法解決我做錯的事情,可能是命名空間“val”的問題?

您需要將命名空間管理器傳遞給 SelectNodes() 方法。

編輯:更正代碼

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

只需將您的 Xpath 更改為:

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

要么:

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

您的 xpath 查詢字符串應該是:

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

或者更簡潔地說,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM