nanthil
nanthil

Reputation: 65

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.

Upvotes: 0

Views: 3326

Answers (3)

har07
har07

Reputation: 89325

Your attempted xpath tried to find <Block> element having child element <ID>. In xpath, you use @ at the beginning of attribute name to reference an attribute, for example /Block/@ID.

Given a correct xpath expression as parameter, SelectNodes() and SelectSingleNode() are capable of returning attributes. Here is an example :

var xml = @"<Block ID=""Ar0010100"" BOX=""185 211 825 278"" ELEMENT_TYPE=""h1"" SEQ_NO=""0"" />";
var doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList idList = doc.SelectNodes("/Block/@ID");
foreach(XmlNode id in idList)
{
    Console.WriteLine(id.Value);
}

Demo

Upvotes: 1

user786
user786

Reputation: 4374

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

Upvotes: 1

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34244

The problem is that ID is actually neither child nor part.
It's a node's attribute. You can access it this way:

doc.SelectSingleNode("/Block").GetAttribute("ID")
// or 
doc.SelectSingleNode("/Block").Attributes["ID"].Value

Of course, you can iterate through them:

foreach (XmlElement element in doc.SelectNodes("/Block"))
{ 
    Console.WriteLine(element.GetAttribute("ID"));
}

You also can ensure that it contains ID attribute, so, you won't get NullReferenceException or other exception. Use the following XPath:

foreach (XmlElement element in doc.SelectNodes("/Block[@ID]"))
{ 
    Console.WriteLine(element.GetAttribute("ID"));
}

Upvotes: 1

Related Questions