如何使用 XPathSelectElement 进行查询
How to query with XPathSelectElement
我有以下类型的 XML,其中包含大量 DocType 值:
<InvalidDocTypes>
<DocType>DocType1</DocType>
<DocType>DocType2</DocType>
</InvalidDocTypes>
我正在尝试使用以下方法在 XML 中查询特定文档类型:
document.PriorDocumentType = "DocType1"
var node = doc.XPathSelectElement("//InvalidDocTypes[DocType='" + document.PriorDocumentType + "']");
当 XML 中没有值时,我只希望节点为 null,但我总是得到 null。对 XML 使用 Linq 查询会更好,还是我对 XPathSelectElement 做错了什么。任何帮助,将不胜感激。谢谢
我测试了您的代码,它似乎可以正常工作 - 请验证下面的控制台应用程序。当 DocType 存在时打印整个 InvalidDocTypes 元素,不存在时打印 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);
}
}
}
我有以下类型的 XML,其中包含大量 DocType 值:
<InvalidDocTypes>
<DocType>DocType1</DocType>
<DocType>DocType2</DocType>
</InvalidDocTypes>
我正在尝试使用以下方法在 XML 中查询特定文档类型:
document.PriorDocumentType = "DocType1"
var node = doc.XPathSelectElement("//InvalidDocTypes[DocType='" + document.PriorDocumentType + "']");
当 XML 中没有值时,我只希望节点为 null,但我总是得到 null。对 XML 使用 Linq 查询会更好,还是我对 XPathSelectElement 做错了什么。任何帮助,将不胜感激。谢谢
我测试了您的代码,它似乎可以正常工作 - 请验证下面的控制台应用程序。当 DocType 存在时打印整个 InvalidDocTypes 元素,不存在时打印 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);
}
}
}