XmlDocument - 带命名空间的SelectSingleNode

时间:2014-03-20 13:53:12

标签: c#

这是我的代码:

XmlTextReader reader = new XmlTextReader(xmlPath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
XmlNode root = xmlDoc.DocumentElement;

XmlNode node = root.SelectSingleNode("marketingid");

有效的XML:

<confirmsubmit>
    <marketingid>-1</marketingid>
</confirmsubmit>

不起作用的XML:

<confirmsubmit xmlns="http:....">
    <marketingid>-1</marketingid>
</confirmsubmit>

处理xmlns属性的方法是什么,我该如何解析它?

它与命名空间有关吗?

修改 这是有效的代码:

XmlTextReader reader = new XmlTextReader(xmlPath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);

XmlNode book = xmlDoc.SelectSingleNode("/ns:confirmsubmit/ns:marketingid", nsmgr);

这个XPath比看起来更复杂,我建议像我这样的初学者阅读:http://www.w3schools.com/xpath/xpath_syntax.asp

3 个答案:

答案 0 :(得分:4)

您需要在游戏中添加XmlNamespaceManager实例:

public class Sample
{
 public static void Main()
{

  XmlDocument doc = new XmlDocument();
  doc.Load("booksort.xml");

  //Create an XmlNamespaceManager for resolving namespaces.
  XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
  nsmgr.AddNamespace("bk", "urn:samples");

  //Select and display the value of all the ISBN attributes.
  XmlNodeList nodeList;
  XmlElement root = doc.DocumentElement;
  nodeList = root.SelectNodes("/bookstore/book/@bk:ISBN", nsmgr);
  foreach (XmlNode isbn in nodeList){
    Console.WriteLine(isbn.Value);
  }

}

}

http://msdn.microsoft.com/es-es/library/4bektfx9(v=vs.110).aspx

答案 1 :(得分:0)

以下是从Linq到XML的方法。简短

    const string xml = @"<confirmsubmit xmlns='http:....'>
                           <marketingid>-1</marketingid>
                         </confirmsubmit>";

    XElement element = XElement.Parse(xml);
    var requestedElement = element.Elements().FirstOrDefault(x => x.Name.LocalName.Equals("marketingid"));

答案 2 :(得分:-1)

xmlns属性用于XHTML并定义文档的命名空间。你可以解析它:

XDocument xdoc = XDocument.Load(xmlPath);
var attrib = xdoc.Root.Attribute("xmlns").Value;