【问题标题】:Read XML file just like python's lxml with C#?用 C# 像 python 的 lxml 一样读取 XML 文件?
【发布时间】:2010-11-03 14:07:04
【问题描述】:
  <Connections>
     <Connection ID = "1" Source="1:0" Sink="4:0"/>
     <Connection ID = "2" Source="2:0" Sink="4:1"/>
     <Connection ID = "3" Source="2:0" Sink="5:0"/>
     <Connection ID = "4" Source="3:0" Sink="5:1"/>
     <Connection ID = "5" Source="4:0" Sink="6:0"/>
     <Connection ID = "6" Source="5:0" Sink="7:0"/>
  </Connections>

当我需要从之前的XML代码中获取信息时,可以使用Python的lxml如下。

def getNodeList(self):
    connection = self.doc.find('Connections')
    cons = connection.find('Connection')

    for con in cons.iter():
        con.get("ID") # get attribute
        ...
  • 我可以使用哪些 C# 库/函数来获取诸如 python 的 lxml 之类的信息?我的意思是,我可以在 C# 中使用 find()/iter() 或类似的东西吗?
  • 有哪些C#库类似于python的lxml?

添加

根据 dtb 的回答,我可以得到我需要的东西。

using System;
using System.Xml;
using System.Xml.Linq;

namespace HIR {
  class Dummy {

    static void Main(String[] argv) {

      XDocument doc = XDocument.Load("test2.xml");

      var connection = doc.Descendants("Connections"); // .First();
      var cons = connection.Elements("Connection");

      foreach (var con in cons)
      {
        var id = (string)con.Attribute("ID");
        Console.WriteLine(id);
      }
    }
  }
}

我必须删除“First()”以避免编译器错误。使用单声道,我可以运行以下命令来获取二进制文件。

dmcs /r:System.Xml.Linq main.cs

【问题讨论】:

    标签: c# python xml lxml


    【解决方案1】:

    你想使用LINQ-to-XML:

    void GetNodeList()
    {
        var connection = this.doc.Descendants("Connections").First();
        var cons = connection.Elements("Connection");
    
        foreach (var con in cons)
        {
            var id = (string)con.Attribute("ID");
        }
    }
    

    【讨论】:

      【解决方案2】:

      我会使用XElement:

      var xml = XElement.Parse(xmlString);
      
      foreach (var connection in xml.Elements("Connection"))
      {
          Console.WriteLine(connection.Attribute("ID").Value);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-23
        • 1970-01-01
        相关资源
        最近更新 更多