Home > Net >  C# Select XML Attributes
C# Select XML Attributes

Time:02-10

I want to select some Attributes out of a Node in XML with C#. My XML Looks like this:

<itemdata>
   <items>
      <item id="1" name="table">
         <cost>200</cost>
         <category>5</category>
         <type>2</type>
      </item>
      <item id="2" name="chair">
         <cost>100</cost>
         <category>4</category>
         <type>6</type>
      </item>
      <item id="3" name="lamp">
         <cost>700</cost>
         <category>2</category>
         <type>3</type>
      </item>
   </items>
</itemdata>

And my Code in C# looks like this:

XmlDocument document = new XmlDocument();
document.Load("c:/dir/itemdata.xml");

foreach(XmlNode node in document.SelectNodes("//item/@name")) {
   string innerText = node.InnerText;
}

How could I display for example the Attributes "cost" or "type" within the same foreach loop?

CodePudding user response:

    foreach(XmlNode node in document.SelectNodes("//item")) {
        var cost = node.SelectSingleNode("./cost").InnerText;
        var type = node.SelectSingleNode("./type").InnerText;
        Console.WriteLine(cost);
        Console.WriteLine(type);
    }

CodePudding user response:

Please try the following solution.

It is using LINQ to XML API, available in the .Net Framework since 2007. No need to use somewhat outdated XML API.

c#

void Main()
{
    const string filename = @"e:\Temp\itemdata.xml";

    XDocument xdoc = XDocument.Load(filename);

    var Item = xdoc.Descendants("item");

    foreach (var elem in Item.Elements())
    {
        Console.WriteLine($"{elem.Name}='{elem.Value}'");
    }
}
  •  Tags:  
  • Related