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

本文关键字:元素 孙元素 获取 XML | 更新日期: 2023-09-27 18:28:38

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

测试项目:

<?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>

然后我试着从文件中读取。我搜索了获取子节点和grand-child节点的方法,发现我可以使用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");

但CCD_ 4未被识别。我做错了什么?

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

您还需要添加System.Xml.XPath命名空间

using System.Xml.XPath;

之后尝试低于

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()

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