前言
在项目中,通过接口调用的返回的xml字符串解析,xml文件结构如下图:
<?xml version="1.0" encoding="UTF-8"?>
<XXList version="2.0" xmlns="http://**********">
<XXNode>
<id>1</id>
<XXName>Name1</XXName>
</XXNode>
<XXNode>
<id>2</id>
<XXName>Name2</XXName>
</XXNode>
<XXNode>
<id>3</id>
<XXName>Name3</XXName>
</XXNode>
</XXList>
使用SelectSingleNode获取节点时,出现结果总是为空的情况。
用TagName
我是通过查找TagName实现了后续的功能,主要是因为,我这里只需要“id”数据,所以实现方式:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstr);
XmlNodeList nodeList = doc.GetElementsByTagName("id");
//遍历输出.
foreach (XmlNode node in nodeList)
{
string id = node.InnerText;
}
通过GetElementsByTagName函数查找出节点列表,是完全OK的。
更好的解决
虽然上面的实现方式满足当前的需求,但是要是后续不满足也很蛋疼,经过一段时间的研究,发现是由于xmlns引起,即xml文件的命名空间。
加上命名空间的处理就可以解决,获得正常的数据,不再是NULL:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstr);
XmlNamespaceManager xmlns = new XmlNamespaceManager(doc.NameTable);
xmlns.AddNamespace("nn", "http://**********");
XmlNode Nlist = doc.SelectSingleNode("nn:XXList", xmlns);
XmlNodeList nodeList = Nlist.ChildNodes;
foreach (XmlNode node in nodeList)
{
string id = node.SelectSingleNode("nn:id", xmlns).InnerText;
}