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