使用 XDocument 搜索和提取数据
我从 sql 返回一个包含多个地址的 xml 字符串,下面是返回内容的示例:
<Addresses>
<Address>
<LetterQueueOID>2</LetterQueueOID>
<Address1>115 MORNINGVIEW TRL</Address1>
<Address2>SCARBOROUGH, </Address2>
<Address3>M1B5L2</Address3>
<City>SCARBOROUGH</City>
<PostalCode>M1B5L2</PostalCode>
</Address>
<Address>
<LetterQueueOID>1</LetterQueueOID>
<Address1>GD PO BOX 685</Address1>
<Address2>THORNBURY, ON</Address2>
<Address3>N0H2P0</Address3>
<City>THORNBURY</City>
<ProvinceOrState>ON</ProvinceOrState>
<CountryCode>Ca</CountryCode>
<PostalCode>N0H2P0</PostalCode>
</Address>
</Addresses>
我想使用 LINQ 来查询此 xml 字符串以获取特定的 LetterQueueOID,即 选择地址(作为字符串),其中 LetterQueueOID = 2。
我所知道的是我可以使用 XDocument,但我无法确切地弄清楚如何获得我想要的内容:
XDocument addresses = XDocument.Parse((string)returnScalar);
IEnumerable<XElement> items = addresses.Root.Elements("Address").ToList();
I am returning back from sql an xml string of multiple addresses, here is an example of what is returning back:
<Addresses>
<Address>
<LetterQueueOID>2</LetterQueueOID>
<Address1>115 MORNINGVIEW TRL</Address1>
<Address2>SCARBOROUGH, </Address2>
<Address3>M1B5L2</Address3>
<City>SCARBOROUGH</City>
<PostalCode>M1B5L2</PostalCode>
</Address>
<Address>
<LetterQueueOID>1</LetterQueueOID>
<Address1>GD PO BOX 685</Address1>
<Address2>THORNBURY, ON</Address2>
<Address3>N0H2P0</Address3>
<City>THORNBURY</City>
<ProvinceOrState>ON</ProvinceOrState>
<CountryCode>Ca</CountryCode>
<PostalCode>N0H2P0</PostalCode>
</Address>
</Addresses>
I want to use LINQ to query this xml string for specific LetterQueueOID's , i.e.
Select Address(as a string) where LetterQueueOID = 2.
All I've figured out is that i can use XDocument, but i can't figure out exactly how to get what I want:
XDocument addresses = XDocument.Parse((string)returnScalar);
IEnumerable<XElement> items = addresses.Root.Elements("Address").ToList();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用Where 扩展方法的lambda 表达式。这里我得到的是 id 为 2 的地址,仅作为示例
try a lambda expression with the Where extension method. here i'm getting the address with id 2, just as an example
好吧,您可以这样做:
但是,这将为您提供所有相关的
元素。您说您想以字符串形式返回地址 - 但以什么格式?
您可以像这样连接字符串:
Well, you can do:
However, that will get you all the relevant
<Address>
elements. You say you want to get the address back as a string - but in what format?You could concatenate the strings like this: