【问题标题】:Linq to XML QuestionLinq to XML 问题
【发布时间】:2011-04-06 02:02:10
【问题描述】:
鉴于以下 XML,我可以使用什么查询将 preapprovalKey 的值提取到字符串变量中?对 LINQ to XML 来说还是有点新意。
<?xml version="1.0" encoding="UTF-8" ?>
- <ns2:PreapprovalResponse xmlns:ns2="http://svcs.paypal.com/types/ap">
- <responseEnvelope>
<timestamp>2011-04-05T18:35:32.952-07:00</timestamp>
<ack>Success</ack>
<correlationId>7cec030fa3eb2</correlationId>
<build>1655692</build>
</responseEnvelope>
<preapprovalKey>PA-9AG427954Y7578617</preapprovalKey>
</ns2:PreapprovalResponse>
【问题讨论】:
标签:
c#
xml
linq
linq-to-xml
【解决方案1】:
XDocument doc = XDocument.Load("test.xml");
string preapprovalKey = doc.Descendants("preapprovalKey").Single().Value;
【解决方案2】:
请参阅下面的示例,它可以帮助您解决问题。 :)
考虑下面这个 XML 是作为 SQL 表的列之一。
<Root>
<Name>Dinesh</Name>
<Id>2</Id>
</Root>
查询的目的是从 XML 中获取名称。在此示例中,我们将获取 'Dinesh' 作为值。
var Query = (from t in dbContext.Employee.AsEnumerable()
where t.active == true
select new Employee
{
Id = t.AtpEventId,
Name = XDocument.Parse(t.Content).Descendants("Root").Descendants("Name").ToList().
Select(node => node.Value.ToString()).FirstOrDefault()
});
注意以下几点:-
在上面的 LINQ 中,t.active == true 只是一个例子,如果需要的话,可以做一些条件。
请注意,在上述 LInQ 查询中,始终使用 AsEnumerable(),就像我在
Linq 的第一个文件 query.exmaple(var Query = (from t in dbContext.Employee.AsEnumerable())
Descendants("Root").Descendants("Name") ,这里的Root应该是与XML匹配的Element,而在Root下我们有 Name 元素,这就是我们写的原因
Descendants("Root").Descendants("Name")
如需进一步说明,您可以通过 danish.eggericx@gmail.com 与我联系