我在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”的东西?
答案 0 :(得分:0)
您需要将命名空间管理器传递给SelectNodes() 方法
编辑:更正后的代码
XmlNodeList nodes = root.SelectNodes("/val:Root/SenSet/Entry", nsmgr);
答案 1 :(得分:0)
只需将Xpath更改为:
XmlNodeList nodes1 = root.SelectNodes("/val:Root/SenSet/Entry",nsmgr);
或者:
XmlNodeList nodes = root.SelectNodes("SenSet/Entry");
答案 2 :(得分:0)
您的xpath查询字符串应为:
XmlNodeList nodes = root.SelectNodes("/val:Root/SenSet/Entry", nsmgr);
或更简洁,
XmlNodeList nodes = root.SelectNodes("//SenSet/Entry", nsmgr);