如何从XML元素中获取子元素和孙元素?

Dom*_*oed 8 c# xml xpath visual-studio

所以,我有一个包含多个子元素的XElement.我可以成功声明XElement,并将其写入文件:

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>
Run Code Online (Sandbox Code Playgroud)

然后我试图从文件中读取.我搜索了获取子节点和子节点的方法,并发现我可以使用XElement.XPathSelectElement().问题是,Visual C#不能识别XPathSelectElement为XElement的方法.我搜索了该方法的用法示例,他们都说要使用XElement.XPathSelectElement.

例如,我尝试过:

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

string get_string = x_el.XPathSelectElement("child/grand-child");
Run Code Online (Sandbox Code Playgroud)

......但XPathSelectElement不被承认.我究竟做错了什么?

Dam*_*ith 5

您需要添加System.Xml.XPath命名空间,以及

using System.Xml.XPath;
Run Code Online (Sandbox Code Playgroud)

之后尝试下面

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()
Run Code Online (Sandbox Code Playgroud)

或者

var get_string = x_el.XPathSelectElement("child/grand-child").ToString();
Run Code Online (Sandbox Code Playgroud)