gpt4 book ai didi

c# - 获取 XML 元素

转载 作者:太空宇宙 更新时间:2023-11-03 18:09:58 24 4
gpt4 key购买 nike

在以下程序中,helloElem不为空,正如预期的那样。

string xml = @"<root>
<hello></hello>
</root>";

XDocument xmlDoc = XDocument.Parse(xml);
var helloElem = xmlDoc.Root.Element("hello"); //not null

如果给 XML 一个命名空间:
string xml = @"<root xmlns=""namespace"">
<hello></hello>
</root>";

XDocument xmlDoc = XDocument.Parse(xml);
var helloElem = xmlDoc.Root.Element("hello"); //null

为什么 helloElem变为空?在这种情况下如何获得 hello 元素?

最佳答案

当然你可以摆脱namespaces , 见下文:

string xml = @"<root>
<hello></hello>
</root>";

XDocument xmlDoc = XDocument.Parse(xml);
var helloElem = xmlDoc.Descendants().Where(c => c.Name.LocalName.ToString() == "hello");

上面的代码可以处理有或没有 namespaces 的节点.见 Descendants() 想要查询更多的信息。希望这可以帮助。

关于c# - 获取 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17926640/

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