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

标签 c# xml visual-studio xpath

因此,我有一个包含多个子元素的 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>

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

...但无法识别 XPathSelectElement。我做错了什么?

最佳答案

您还需要添加 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();

关于c# - 如何从 XML 元素中获取子元素和孙元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18371136/

相关文章:

c# - 具有通用接口(interface)的通用方法

python - 在 Python 中将 -0.00 转换为 0.00 float

visual-studio - Visual Studio - 在哪里定义自定义路径宏?

c# - 将参数直接传递给成员的构造函数语法

c# - 在 Google Visualization API (JavaScript) 中动态添加行

c# - 清理 TPL 中的 CallContext

c# - 如何使用 xsd.exe/c 输出

python - 将 XML 属性转换为列表,就像在 Python 中使用参数到函数中一样

c# - 当我运行我的 C# 应用程序时,Visual Studio 报告它加载了一个托管二进制文件(看起来像)一个随机生成的名称

windows - 找不到 Visual Studio 2017 依赖的 .dll