user2998990
user2998990

Reputation: 980

how to get Name of the node in XML

<Tables>
  <Table name="Test">
    <tablename>TestTable</tablename>
    <refTable>NULL</refTable>
    <refTableIDColumn>NULL</refTableIDColumn>
  </Table>
</Tables>

Above is my XML input. I am able to extract nodes by Table name using below code

XmlNodeList companyList = doc.GetElementsByTagName("Table");

I want the name which is given to Table node. For eg here I want the Text as "Test". How do I get that. Please help.

Upvotes: 0

Views: 1963

Answers (2)

Manfred Radlwimmer
Manfred Radlwimmer

Reputation: 13384

The XmlNodeList can be filtered/queried with XPath. In your case, you want to look for the name attribute of a Table which would like this for example:

var tableNames = doc.SelectNodes("//Table/@name");

You result will be a collection of XmlAttributes, the actual name can be retrieved with the InnerText property.

See it in action on DotNetFiddle

btw: your last xml-tag is missing a /

Upvotes: 1

Mostafiz
Mostafiz

Reputation: 7352

Suppose your xml file in C drive named test.xml then you can get the name using this code

XDocument xDoc = XDocument.Load(@"C:\test.xml");

XElement root = xDoc.Element("Tables");    // select root
XElement elm1 = root.Element("Table");    // get elm1 == null
string name = elm1.Attribute("name").Value;

Upvotes: 1

Related Questions