XmlDocument -选择带有名称空间的tsinglenode

本文关键字:空间 tsinglenode 有名称 选择 XmlDocument | 更新日期: 2023-09-27 17:51:03

这是我的代码:

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

XmlDocument -选择带有名称空间的tsinglenode

您需要在游戏中添加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);
      }
    }
}

下面是如何从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"));

xmlns属性用于XHTML并定义文档的名称空间。您可以这样解析它:

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