【问题标题】:XmlDocument.SelectNodes and XPath NavigationXmlDocument.SelectNodes 和 XPath 导航
【发布时间】:2017-06-12 13:59:45
【问题描述】:

我有类似这样的 XML 代码:

  <BookStore xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Book>
    <bookGenre>Fantasy</bookGenre>
    <bookTitle>A Storm of Swords</bookTitle>
    <authorInformation>
      <authorId>12345</authorId>
      <authorName>
        <firstName>George</firstName>
        <middleInitial>R.R.</middleInitial>
        <lastName>Martin</lastName>
      </authorName>
    </authorInformation>
  </Book>
  <customer>
    <customerData />
  </customer>
</BookStore>

&lt;customer&gt;node 可能有也可能没有子节点,具体取决于用户输入。

我正在尝试使用 XmlDocument.SelectNodes 和 XPath 导航来选择 &lt;BookStore&gt;&lt;customer&gt; 以及 &lt;customer&gt; 中包含的任何节点。

几个小时以来,我一直在四处寻找和阅读有关 XPath 和 .SelectNodes 的信息,但似乎仍然没有完全理解它们是如何工作的。有人可以解释如何使用它们或我如何在我的情况下使用它们吗?如果还有其他方法可以解决我的问题,我也愿意接受! (我使用的是 C#)

编辑:这是我根据阅读的内容尝试过的内容

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
XmlNode root = doc.DocumentElement;

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

XmlNodeList nodeList = root.SelectNodes("descendant::customer:child::Node");

doc.Save(Console.Out); 

【问题讨论】:

  • 请向我们展示您的尝试。
  • 添加了我试过的代码。
  • 那么当你调用doc.LoadXml() 并给它一个文件名而不是一个XML 字符串时会发生什么?我知道会发生什么。我在问你为什么在你尝试解析 XML 时没有在你的问题中说任何关于获取异常的内容。
  • 使用 LINQ to XML 应该是 var customerData = XDocument.Load(fileName).Descendants("customerData");
  • 哦,对不起,这让我很困惑,我曾经使用一个文件,但后来我只是将 fileName 更改为接收 XML 字符串而不更改变量名,我将对其进行编辑:P

标签: c# xml xpath selectnodes


【解决方案1】:

试试 xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication62
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement customer = doc.Descendants("customer").FirstOrDefault();

            Boolean children = customer.HasElements;

        }

    }
}

【讨论】:

  • 是否可以使用 XML 字符串作为输入而不是文件来执行类似的操作?
  • 当然。使用 XDocument.Parse(string) 而不是 xDocument.Load(filename or uri)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
相关资源
最近更新 更多