Search code examples
c#xmlxml-parsingxmlnodexml-attribute

Read XML Attribute using C#


    <Block ID="Ar0010100" BOX="185 211 825 278" ELEMENT_TYPE="h1" SEQ_NO="0" />

This is an example from my XML code. In C# I need to store ONLY ID'S inside of a block element in one variable, and ONLY Box's inside of a block element. I have been trying to do this for two days, and I don't know how to narrow down my question.

XmlNodeList idList = doc.SelectNodes("/Block/ID");

doesn't work... Any version of doc.selectnode, doc.GetElementBy... doesn't return the right element/children/whatever you call it. I'm not able to find documentation that tells me what I'm trying to reference. i don't know if ID or BOX are children, if they're attributes or what. This is my first time using XML, and I can't seem to narrow down my problem.


Solution

  • You can simply use following code

     XmlNodeList elemList = doc.GetElementsByTagName("Your Element");
    for (int i = 0; i < elemList.Count; i++)
    {
        string attrVal = elemList[i].Attributes["ID"].Value;
    }
    

    Demo: https://dotnetfiddle.net/5PpNPk

    the above code is taken from here Read XML Attribute using XmlDocument