4

请帮助我解决下面提到的具有 xml 的场景,我想要 C# LINQ 中的代码

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <Countries>
    <Country name="India">
      <state id="1"> Tamilnadu</state>
      <state> Karnataka</state>
    </Country>
    <Country name="America">
      <state id="1"> WI</state>
      <state> AW </state>
    </Country>
    <Country name="Africa">
      <state id="1"> Melbourne</state>
      <state> sydney </state>
    </Country>
  </Countries>
</root>

由于我能够获取属性名称 =“印度”,如何通过 LINQ 获取属性 id=1 的状态?以及如何给出 id=1 我的意思是没有“1”的数值

4

4 回答 4

2

试试下面的。

XDocument xml = XDocument.Load(file);

XElement state = xml.Root.Descendants("Country")
    .First(c => c.Attribute("name").Value == "India")
    .Descendants("state")
    .First(s => (int)s.Attribute("id") == 1);

下次发布您首先尝试过的内容,以便我们可以帮助您编写代码。

我也这样做没有空检查。如果找不到值,它将在First(). 由您自己进行安全检查。

于 2013-08-28T16:27:30.697 回答
2

如果您正在使用C#,您可以执行以下操作:

 XDocument document = XDocument.Load("filePath");

 var states = (from state in document.Root.Descendants("state")
               where state.Attribute("id") != null && state.Attribute("id").Value == "1" 
               select state).ToList();
于 2013-08-28T15:22:51.620 回答
2

您可以执行以下操作:

空检查很重要,因为根据您的结构判断,如果没有空检查,您将得到一个NullReferenceException.

XDocument xml = XDocument.Load("yourFileLocation");

var items = document.Root.Descendants("state")
    .Where(s => s.Attribute("id") != null && s.Attribute("id").Value == "1")
    .ToList();
于 2013-08-28T15:50:25.433 回答
0

我发现现有的答案过于冗长和冗长。想象一下,如果您要根据多个属性进行选择,会发生什么?

最紧凑且同时具有表现力的解决方案是使用 XPath 扩展(来自System.Xml.XPath命名空间)。

例如,要在印度获得 id=1 的州:

var xdoc = XDocument.Load(file);
foreach (var element in xdoc.XPathSelectElements("//Country[@name='India']/state[@id=1]"))
{
    Console.WriteLine("State " + element.Value + ", id " + (int)element.Attribute("id"));
}

要获取分配了任何 id 的所有国家/地区的所有州:

foreach (var element in xdoc.XPathSelectElements("//state[@id]"))
{
    Console.WriteLine("State " + element.Value + ", id " + (int)element.Attribute("id"));
}

等等。

您可以在此处找到 XPath 规范。

于 2013-08-29T08:35:09.450 回答