【问题标题】:How to traverse through attributes in xml through LINQ如何通过LINQ遍历xml中的属性
【发布时间】:2013-08-28 15:20:00
【问题描述】:

请帮助我解决下面提到的具有 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 的状态,因为我能够获取属性 name="India"?以及如何给出 id=1 我的意思是没有“1”的数值

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    您可以执行以下操作:

    空值检查很重要,根据你的结构判断,如果没有空值检查,你会得到一个NullReferenceException

    XDocument xml = XDocument.Load("yourFileLocation");
    
    var items = document.Root.Descendants("state")
        .Where(s => s.Attribute("id") != null && s.Attribute("id").Value == "1")
        .ToList();
    

    【讨论】:

      【解决方案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() 上消失。由您自己进行安全检查。

      【讨论】:

        【解决方案3】:

        如果您使用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();
        

        【讨论】:

        • var query = from s in element.Root.Descendants("state") where s.Attribute("id").Value =="1" select s; - 面向对象引用未设置为 id=1 的第二个状态的实例
        • @rajalakshmi - 您需要添加 null 签入。请参阅我的编辑。
        【解决方案4】:

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

        同时最紧凑和最具表现力的解决方案是使用 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 规范here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-09-27
          • 1970-01-01
          • 1970-01-01
          • 2013-07-05
          • 1970-01-01
          相关资源
          最近更新 更多