具有公共值的 XML SelectNodes,迭代
Posted
技术标签:
【中文标题】具有公共值的 XML SelectNodes,迭代【英文标题】:XML SelectNodes with common values, iteratively 【发布时间】:2021-06-04 23:25:59 【问题描述】:我有一个登记选民的 XML 文档,并且可能有多个人在一个地址。我想为每个不同的地址(数字和街道)迭代地选择节点。我的目标是能够将一个地址的所有居民的姓名组合到一行中。例如“罗伯特和奥尔加 bbbbbb”,或“Jennifer eeeee 和 James fffff”,或者只是“Desmond aaaaaa”。 我只需要 XPath 查询方面的帮助。如果 LINQ 是答案,我也想听听。你能帮我解决这个问题吗?
<addresses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<address>
<LastName>aaaaaa</LastName>
<FirstName>DESMOND</FirstName>
<Number>311</Number>
<Street>APPLETON ST</Street>
</address>
<address>
<LastName>bbbbbb</LastName>
<FirstName>OLGA</FirstName>
<Number>315</Number>
<Street>APPLETON ST</Street>
</address>
<address>
<LastName>bbbbbb</LastName>
<FirstName>ROBERT</FirstName>
<Number>315</Number>
<Street>APPLETON ST</Street>
</address>
<address>
<LastName>cccccc</LastName>
<FirstName>YUJI</FirstName>
<Number>316</Number>
<Street>APPLETON ST</Street>
</address>
<address>
<LastName>dddddd</LastName>
<FirstName>MARK</FirstName>
<Number>319</Number>
<Street>APPLETON ST</Street>
</address>
<address>
<LastName>dddddd</LastName>
<FirstName>HILARY</FirstName>
<Number>319</Number>
<Street>APPLETON ST</Street>
</address>
<address>
<LastName>eeeeee</LastName>
<FirstName>JENNIFER</FirstName>
<Number>320</Number>
<Street>APPLETON ST</Street>
</address>
<address>
<LastName>ffffff</LastName>
<FirstName>JAMES</FirstName>
<Number>320</Number>
<Street>APPLETON ST</Street>
</address>
<address>
<LastName>gggggg</LastName>
<FirstName>NORA</FirstName>
<Number>323</Number>
<Street>APPLETON ST</Street>
</address>
</addresses>```
【问题讨论】:
【参考方案1】:尝试关注。大多数人会使用效率不高的 Xml 序列化。在这种情况下,我更喜欢 Xml Linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
class Program
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
XDocument doc = XDocument.Load(FILENAME);
List<Address> addresses = doc.Descendants("address").Select(x => new Address()
lastName = (string)x.Element("LastName"),
firstName = (string)x.Element("FirstName"),
number = (int)x.Element("Number"),
street = (string)x.Element("Street")
).ToList();
var groups = addresses.GroupBy(x => new number = x.number, street = x.street ).ToList();
public class Address
public string lastName get; set;
public string firstName get; set;
public int number get; set;
public string street get; set;
【讨论】:
绝对完美,非常感谢jdweng!!以上是关于具有公共值的 XML SelectNodes,迭代的主要内容,如果未能解决你的问题,请参考以下文章
获取 xml 节点值尝试使用 SelectSingleNode 和 SelectNodes 使用 c#
xml文件节点读取时,selectNodes总是在根节点下查找的问题