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

Alexander Bell
  • 7,842
  • 3
  • 26
  • 42
nanthil
  • 65
  • 1
  • 4
  • 11
  • Hope this helps you solve your problem http://stackoverflow.com/questions/1600065/how-to-read-attribute-value-from-xmlnode-in-c – m_d_p29 Jun 01 '15 at 03:26

3 Answers3

1

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"));
}
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
1

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

Community
  • 1
  • 1
user786
  • 3,902
  • 4
  • 40
  • 72
1

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

har07
  • 88,338
  • 12
  • 84
  • 137