如何使用 XPathSelectElement 提取元素

How to Extract an Element using XPathSelectElement

我正在从 xml 文档中提取一个元素,但它正在返回 null

<?xml version="1.0" encoding="utf-8"?>
<Test1 
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-test"
   xmlns="https://www.google.com/partner/testt.xsd">

  <Test2>OK</Test2>
  <Test3>1439379003</Test3>
</Test1>

我正在尝试提取 test2 元素,但它返回 null

var responseXdoc = XDocument.Parse(response);
var statusElement = responseXdoc.XPathSelectElement("/Test1/Test2");

结果 statusElementnull 但我期待 Ok

命名空间中的问题

xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://www.google.com/partner/testt.xsd (Its my guess)

您的 XML 具有范围内的元素隐式继承的默认名称空间。要使用 XPath 引用命名空间中的元素,您需要使用命名空间前缀,您需要在 XmlNamespaceManager :

之前注册
var nsManager = new XmlNamespaceManager(new NameTable());

nsManager.AddNamespace("d", "https://www.insuranceleads.com/partner/PricePresentationResult.xsd");

var statusElement = responseXdoc.XPathSelectElement("/d:Test1/d:Test2", nsManager);

dotnetfiddle demo

或者,您可以使用 XNamespace 和 LINQ API 来做同样的事情,例如:

XNamespace d = "https://www.insuranceleads.com/partner/PricePresentationResult.xsd";
var statusElement = responseXdoc.Element(d + "Test1").Element(d + "Test2");