Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read XML file just like python's lxml with C#?

Tags:

python

c#

xml

lxml

  <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>

When I need to get info from the previous XML code, Python's lxml can be used as follows.

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

    for con in cons.iter():
        con.get("ID") # get attribute
        ...
  • What C# libraries/function can I use for getting the info like python's lxml? I mean, can I use find()/iter() or similar with C#?
  • What C# libraries are similar to python's lxml?

ADDED

Based on dtb's answer, I could get what I needed.

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);
      }
    }
  }
}

I had to remove the 'First()' to avoid compiler error. With mono I could run the following to get the binary.

dmcs /r:System.Xml.Linq main.cs
like image 833
prosseek Avatar asked Aug 31 '25 21:08

prosseek


1 Answers

You want to use 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");
    }
}
like image 77
dtb Avatar answered Sep 03 '25 11:09

dtb