嗨,我有下面的代码片段正在工作,当没有可用的名称空间时,但是如果我使它可用,则它不返回任何值。
xml文件:Person.xml
<?xml version="1.0" encoding="utf-8" ?>
<Persons>
<Person name="John Smith">
<Age>30</Age>
<Gender>Male</Gender>
</Person>
<Person name="Mike Folley">
<Age>25</Age>
<Gender>Male</Gender>
</Person>
<Person name="Lisa Carter">
<Age>22</Age>
<Gender>Female</Gender>
</Person>
</Persons>
将上述xml文件加载到xml文档中
string xmlstr1 = AppDomain.CurrentDomain.BaseDirectory + "Person.xml";
XmlDocument doc = new XmlDocument();
doc.Load(xmlstr1);
XmlNodeList personNodes = doc.DocumentElement.SelectNodes("Person");
如果我为文档添加名称空间,并尝试使用xath获取值,它将无法正常工作。
为根添加名称
<?xml version="1.0" encoding="utf-8" ?>
<Persons xmlns="www.google.com">
<Person name="John Smith">...
.....
然后我正在尝试使用以下代码获取值,但没有结果。
XmlNode root = doc.DocumentElement;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", root.NamespaceURI);
XmlNodeList node = doc.DocumentElement.SelectNodes("Person", nsmgr);
命名空间没有前缀,这增加了一些混乱。
创建具有匹配URI和您自己的前缀的名称空间,然后在查询中使用该前缀。
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr;
nsmgr = new XmlNamespaceManager(nt);
string strURI = "www.google.com"; // the default namespace, must match your doc.
nsmgr.AddNamespace("g", strURI); // add your own prefix (anything you want really)
// Query with the "g" prefix, that you just defined.
XmlNode ndNode = doc.SelectSingleNode("//g:Person", nsmgr);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句