我有一个XML:
<?xml version="1.0" encoding="UTF-8"?>
<ticket>
<comments type="array">
<comment>
<attachments type="array">
<attachment>
<url>I NEED WHATEVER IS IN HERE</url>
</attachment>
</attachments>
</comment>
<comment>
<attachments type="array">
<attachment>
<url>I NEED WHATEVER IS IN HERE</url>
</attachment>
</attachments>
<comment>
</comments>
</ticket>
如何获取网址标记内的内容并将其添加到<List>
?我正在使用C#。
答案 0 :(得分:3)
使用:
var result = XDocument.Parse(inputXml)
.DescendantNodes().OfType<XText>().Select(e => e.Value).ToList();
或者使用XPath:
var result = ((IEnumerable)XDocument.Parse(input).XPathEvaluate("//text()"))
.Cast<XText>().ToList();
仅从url
元素使用中检索文本:
var result = XDocument.Parse(inputXml)
.Descendants("url").Select(e => e.Value).ToList();
或更改以上XPath://url/text()
答案 1 :(得分:2)
using (StringReader sr = new StringReader(xml_content))
{
XDocument xdoc = XDocument.Load(sr);
IList<string> values = xdoc.XPathSelectElements("ticket/comments/attachments/url").Select(e => e.Value).ToList();
}
或者,根据您评论中的用例:
var doc = new XmlDocument();
doc.LoadXml(xml_content);
IList<string> values = doc.SelectNodes("ticket/comments/attachments/url")
.Cast<XmlElement>().Select(e => e.InnerText).ToList();
答案 2 :(得分:0)
或者您可以使用var values = xdoc.SelectSingleNode(“ticket / comments / attachments / url”)。InnerXml;