[英]How to get the String of a XML node in C#
enter code herein the XML document :在 XML 文档中输入代码:
<foo>
<bar><para> test </para> </bar>
<bar>text</bar>
<bar>stackoverflow</bar>
</foo>
I am trying to parse it and only get the Strings in bar;我正在尝试解析它,并且只获取 bar 中的字符串; by using this way:
通过使用这种方式:
[function where node is the foo] [节点为 foo 的函数]
foreach (XmlNode subNode in node.ChildNodes)
{
if (subNode.Name == "bar")
{
if (!String.IsNullOrWhiteSpace(subNode.InnerText))
Debug.WriteLine(subNode.Name + " - " subNode.InnerText);
}
} }
However it gives me test但是它给了我测试
Thanks谢谢
This is what you are looking for (EDITTED based on you updated question)这就是您正在寻找的(根据您更新的问题进行编辑)
XDocument doc = XDocument.Load(path to your xml file);
XNamespace ns = "http://docbook.org/ns/docbook";
var result = doc.Root.Descendants(ns + "para")
.Where(x => x.FirstNode.NodeType == System.Xml.XmlNodeType.Text)
.Select(x => x.Value)
.ToList();
In your updated xml I see you are using a namespace so the name of your node is not para
but it's theNameSpace + "para"
.在您更新的 xml 中,我看到您正在使用命名空间,因此您的节点名称不是
para
,而是theNameSpace + "para"
。 The namespace is defined in the first line of your xml file.命名空间在 xml 文件的第一行中定义。 Also you can see this sample too.
你也可以看到这个样本。
Do you want "test"?你想“测试”吗? Try following :
尝试以下:
string input =
"<foo>" +
"<bar><para> test </para> </bar>" +
"<bar>text</bar>" +
"<bar>stackoverflow</bar>" +
"</foo>";
XDocument doc = XDocument.Parse(input);
List<string> bars = doc.Descendants("bar").Where(x => x.NextNode != null).Select(x => (string)((XElement)x.NextNode)).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.