gpt4 book ai didi

c# - 如何使用 XPathSelectElement 提取元素

转载 作者:行者123 更新时间:2023-11-30 21:51:56 25 4
gpt4 key购买 nike

我正在从 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");

result 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");

关于c# - 如何使用 XPathSelectElement 提取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35102323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com