我有一个注册选民的XML文档,一个地址可能有多个人。我想迭代地为每个不同的地址(数字和街道)选择节点。然后,我的目标是能够把一个地址的所有居民的名字集合成一行。例如“Robert and Olga BBBBBB”,或“Jennifer eeeee and James FFFF”,或“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>```
试着跟着。大多数人将使用不是很有效的Xml Serization。在本例中,我更喜欢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; }
}
}