Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get child and grandchild elements from XML element?

So, I have an XElement, that contains multiple child elements. I can successfully declare the XElement, and write it to a file:

Test.project:

<?xml version="1.0" encoding="utf-8"?>
<project>
    <child>
        <grand-child1>
            <great-grand-child1>Hello There!</great-grand-child1>
            <great-grand-child2>Hello World!</great-grand-child2>
        </grand-child1>
        <grand-child2>Testing 123...</grand-child2>
    </child>
</project>

Then I'm trying to read from the file. I searched for ways to get child and grand-child nodes, and found I can use XElement.XPathSelectElement(). The problem is, Visual C# doesn't recognize XPathSelectElement as a method for an XElement. I've searched for usage examples for the method, and they all say to use XElement.XPathSelectElement.

For example, I tried:

x_el = new XElement("project",
    new XElement("child",
        new XElement("grand-child", "Hello World!")
);

string get_string = x_el.XPathSelectElement("child/grand-child");

...but XPathSelectElement is not recognized. What am I doing wrong?

like image 908
Dominoed Avatar asked Aug 22 '13 03:08

Dominoed


1 Answers

You need to add System.Xml.XPath namespace as well like

using System.Xml.XPath;

after that try below

x_el = new XElement("project",
    new XElement("child",
        new XElement("grand-child", "Hello World!")
));
// XPathSelectElement method return XElement not string , use var or XElement 
XElement element = x_el.XPathSelectElement("child/grand-child");
string get_string = element.ToString()

Or

var get_string = x_el.XPathSelectElement("child/grand-child").ToString();
like image 86
Damith Avatar answered Sep 19 '22 12:09

Damith