LINQ to XML 提取嵌套元素
LINQ to XML extract nested elements
我是 LINQ 和 XML 解析的新手,也是 C# 编程的新手。对于以下 XML 结构,我正在尝试提取嵌套元素:
<persons>
<person>
<personNumber>2</personNumber>
<info>free text</info>
<addresses>
<address>
<city>XXX</city>
<location>1</location>
</address>
<address>
<city>YYY</city>
<location>2</location>
</address>
</addresses>
</person>
<person>
<personNumber>3</personNumber>
<info>free text</info>
<addresses>
<address>
<city>XXX</city>
<location>1</location>
</address>
<address>
<city>YYY</city>
<location>2</location>
</address>
</addresses>
</person>
</persons>
我希望能够获取所有 personNumber = 2 的人的所有城市和位置!
像下面这样的东西应该可以工作:
XDocument xmlDoc = XDocument.Load(@"mypath\persons.xml");
var q = from e in xmlDoc.Descendants("person")
where e.Element("personNumber").Value == "2"
let address = e.Descendants("address")
from a in address
select new {
city = a.Element("city").Value,
location = a.Element("location").Value
};
使用 OP 中提供的示例 xml,上述 linq 查询产生以下结果:
[0] = { city = "XXX", location = "1" }
[1] = { city = "YYY", location = "2" }
您可以使用 linq 这样做:
var result = from p in xmlDoc.Descendants("person")
from a in p.Descendants("address")
where p.Element("personNumber").Value == "2"
select new
{
City = a.Element("city").Value,
Location = a.Element("location").Value
};
我是 LINQ 和 XML 解析的新手,也是 C# 编程的新手。对于以下 XML 结构,我正在尝试提取嵌套元素:
<persons>
<person>
<personNumber>2</personNumber>
<info>free text</info>
<addresses>
<address>
<city>XXX</city>
<location>1</location>
</address>
<address>
<city>YYY</city>
<location>2</location>
</address>
</addresses>
</person>
<person>
<personNumber>3</personNumber>
<info>free text</info>
<addresses>
<address>
<city>XXX</city>
<location>1</location>
</address>
<address>
<city>YYY</city>
<location>2</location>
</address>
</addresses>
</person>
</persons>
我希望能够获取所有 personNumber = 2 的人的所有城市和位置!
像下面这样的东西应该可以工作:
XDocument xmlDoc = XDocument.Load(@"mypath\persons.xml");
var q = from e in xmlDoc.Descendants("person")
where e.Element("personNumber").Value == "2"
let address = e.Descendants("address")
from a in address
select new {
city = a.Element("city").Value,
location = a.Element("location").Value
};
使用 OP 中提供的示例 xml,上述 linq 查询产生以下结果:
[0] = { city = "XXX", location = "1" }
[1] = { city = "YYY", location = "2" }
您可以使用 linq 这样做:
var result = from p in xmlDoc.Descendants("person")
from a in p.Descendants("address")
where p.Element("personNumber").Value == "2"
select new
{
City = a.Element("city").Value,
Location = a.Element("location").Value
};