Reputation: 61
I am trying to access element at first level in given xml. I am using below code to access it but it gives me nested one as it come first.
var xml = "<grading>" +
"<leap>" +
"<controlId>1</controlId>" +
"</leap>" +
"<controlId>2</controlId>" +
"</grading>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var node = doc.DocumentElement.SelectSingleNode("//controlId").InnerText;
It is giving me value 1 while i am trying to access value 2 which is inside root node. Do we have any by which we can access it.
Upvotes: 2
Views: 565
Reputation: 3037
var node = doc.DocumentElement.SelectSingleNode("//grading/controlId").InnerText;
Upvotes: 1
Reputation: 1502086
Your XPath expression is
//controlId
That will find all descendants called controlId
. You only want direct children of the element you're calling the method on, so you should use
controlId
So this works:
var node = doc.DocumentElement.SelectSingleNode("controlId").InnerText;
However, I'd strongly recommend using LINQ to XML instead, as a cleaner XML API:
using System;
using System.Xml.Linq;
public class Program
{
public static void Main(string[] args)
{
var xml = @"
<grading>
<leap>
<controlId>1</controlId>
</leap>
<controlId>2</controlId>
</grading>";
XDocument doc = XDocument.Parse(xml);
XElement control = doc.Root.Element("controlId");
Console.WriteLine(control.Value); // 2
}
}
I would avoid using XPath unless you're really trying to use its advanced functionality. To just retrieve an element, attribute etc by name, the LINQ to XML API is simpler and less error-prone (as shown by this question's existence).
Upvotes: 3
Reputation: 1002
I use alot of LINQ TO XML when i am parsing XML. For example to get the root in your set.
string xml = "";
XDocument doc = XDocument.Parse(xml);
XElement elRoot = doc.Root
More resources can be found here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml-overview
Upvotes: 0