如何使用XPathSelectElement进行查询

本文关键字:查询 XPathSelectElement 何使用 | 更新日期: 2023-09-27 18:13:57

我有以下包含大量DocType值的XML类型:

<InvalidDocTypes>
  <DocType>DocType1</DocType>
  <DocType>DocType2</DocType>
</InvalidDocTypes>

我正在尝试使用以下命令查询特定文档类型的XML:

document.PriorDocumentType = "DocType1"
var node = doc.XPathSelectElement("//InvalidDocTypes[DocType='" + document.PriorDocumentType + "']");

当XML中没有值时,我只期望节点为空,但我总是得到一个空。对XML使用Linq查询是否更好,或者我对XPathSelectElement做错了什么?任何帮助都会很感激。由于

如何使用XPathSelectElement进行查询

我测试了你的代码,它似乎是工作-请验证下面的控制台应用程序。当DocType存在时,它打印整个InvalidDocTypes元素,当DocType不存在时打印null:

using System;
using System.Xml.Linq;
using System.Xml.XPath;
namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            var xml = @"<InvalidDocTypes>
  <DocType>DocType1</DocType>
  <DocType>DocType2</DocType>
</InvalidDocTypes>";
            var documentType = "DocType1";
            var xmlDocument = XDocument.Parse(xml);
            var node = xmlDocument.XPathSelectElement("//InvalidDocTypes[DocType='" + documentType + "']");
            Console.WriteLine(node);
        }
    }
}