我正在尝试在 XDocument 对象中使用 LINQ to XML。如何查询下面示例中的结果元素?
<serv:header>
<serv:response>
<serv:result>SUCCESS</serv:result>
<serv:gsbStatus>PRIMARY</serv:gsbStatus>
</serv:response>
</serv:header>
当我使用这样的语句时,我收到异常“附加信息:‘:’字符,十六进制值 0x3A,不能包含在名称中。”
XDocument doc = XDocument.Parse(xml);
string value = doc.Descendants("serv:header").First().Descendants("serv:response").First().Descendants("serv:result").First().Value;
serv
在你的 XML 中是命名空间前缀。它必须与某个标识命名空间的 URI 相关联。在 XML 中查找类似以下的属性:
xmlns:serv="..."
引号内的值将是名称空间。现在,在您的 C# 代码中,您使用该 URI 创建一个XNamespace
object:
private static readonly XNamespace serv = "...";
然后你可以在这样的查询中使用它:
string value = doc
.Descendants(serv + "header").First()
.Descendants(serv + "response").First()
.Descendants(serv + "result").First()
.Value;
顺便说一下,你应该考虑使用.Element()
而不是.Descendants().First()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)