gpt4 book ai didi

c# - 停留在基本的 Linq to XML 查询上

转载 作者:行者123 更新时间:2023-12-02 05:41:55 25 4
gpt4 key购买 nike

我正在尝试从 namecheap 沙箱 api 中提取信息,但无法弄清楚为什么我的 linq 查询不起作用。

这是一个示例响应。

XML

<ApiResponse Status="OK" xmlns="http://api.namecheap.com/xml.response">
<Errors />
<Warnings />
<RequestedCommand>namecheap.domains.check</RequestedCommand>
<CommandResponse>
<DomainCheckResult Domain="google.com" Available="false" />
</CommandResponse>
<Server>WEB1-SANDBOX1</Server>
<GMTTimeDifference>--4:00</GMTTimeDifference>
<ExecutionTime>0.875</ExecutionTime>
</ApiResponse>

C#

var doc = XDocument.Load(url);
var response = (
from r in doc.Root.Descendants("ApiResponse")
where 1==1
select new {
Errors = r.Element("Errors").Value,
Warnings = r.Element("Warnings").Value,
RequestedCommand = r.Element("RequestedCommand").Value,
CommandResponse = r.Element("CommandResponse").Value,
Server = r.Element("Server").Value
}
);

我也用同一个文档尝试过这个查询,只是为了看看一个简单的例子是否有效。

var test = doc.Descendants("RequestedCommand").First().Value;

但是两者都返回null。那我哪里错了?我最终需要了解 CommandResponse 中的顶级元素和更深层次的元素。对此的任何帮助也将不胜感激。

更新

正如 Jon 的回答所提到的,这主要是在引用各种元素时不使用命名空间的问题。还使用了 doc.Elements() 而不是 doc.Root。后代()。

这是更新后的工作版本。

XNamespace ns = "http://api.namecheap.com/xml.response";
var response = (
from r in doc.Elements()
select new
{
Errors = r.Element(ns + "Errors").Value,
Warnings = r.Element(ns + "Warnings").Value,
RequestedCommand = r.Element(ns + "RequestedCommand").Value,
CommandResponse = r.Element(ns + "CommandResponse").Value,
Server = r.Element(ns + "Server").Value
}
);

最佳答案

问题是你在寻找元素、后代等时没有使用命名空间:

XNamespace ns = "http://api.namecheap.com/xml.response";
var doc = XDocument.Load(url);
var response = doc.Root
.Descendants(ns + "ApiResponse")
.Select(r => new {
Errors = r.Element(ns + "Errors").Value,
...
});

(请注意,在 LINQ 中您永远不需要 where 1 == 1...我已从查询表达式语法中更改了它,因为它没有给您任何东西。)

命名空间继承自<ApiResponse>元素作为所有其他元素的默认命名空间,因为它只是 xmlns=...而不是指定别名。

另请注意,如果您向我们展示了整个 XML 文档,那么上面将找不到任何元素,因为您正在请求 ApiReponse。 elements 根元素之下,而它根元素。

关于c# - 停留在基本的 Linq to XML 查询上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10836330/

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