我有一个如下所示的 XML 文档:
<root type="object">
<totalResults type="number">x</totalResults>
<itemsPerPage type="number">x</itemsPerPage>
<startIndex type="number">x</startIndex>
<schemas type="array">
<item type="string">x</item>
</schemas>
<Resources type="array">
<item type="object">
<schemas type="array">
<item type="string">x</item>
</schemas>
<id type="string">x</id>
<externalId type="null"></externalId>
<meta type="object">
<created type="string">x</created>
<location type="string">x</location>
</meta>
<userName type="string">x</userName>
<emails type="array">
<item type="object">
<value type="string">x.x@x.com</value>
<primary type="boolean">x</primary>
</item>
</emails>
</item>
</Resources>
</root>
我正在尝试获取这样的电子邮件地址:
var emails = xmlContent.Root.Elements("Resources").Elements("item").Elements("Emails");
foreach (XElement elem in emails)
{
Console.Write(elem.Value);
}
这是行不通的。关于如何在 C# 中从这种类型的 XML XDocument 获取电子邮件地址有什么想法吗?我浏览了一些论坛和教程,但似乎无法掌握 XPath 等。
最佳答案
XDocument xdoc = XDocument.Load(new StringReader("<root ...")); //// load xml file
var emails = xdoc.Descendants("Resources").Descendants("emails").ToList(); //// select all emails
我正在使用 Descendants
,因为它可以找到任何级别的 child ,并且可以搜索整个子树,但 Elements
只能找到直接的 child
关于c# - XML 获取特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41877776/