将xml中的多个节点转换为List<;字符串>;(C#)
本文关键字:字符串 lt gt List xml 转换 节点 | 更新日期: 2023-09-27 18:25:56
我有以下xml文件:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<termsAndConditions>
<logo>
logo1.gif
</logo>
<link>
https://www.mysite.co.uk/Terms%20and%20Conditions.pdf
</link>
<paragraphs>
<text>
I accept that all the information I have provided is truthful and accurate and I understand that all the information I have provided will be checked and verified. I acknowledge that I have read and accepted all the Terms and Conditions of the site’s Parking Regulations, for full details click here.
</text>
<text>
Paragraph 2
</text>
<text>
Paragraph 3
</text>
<text>
Paragraph 4
</text>
</paragraphs>
</termsAndConditions>
现在我可以使用以下方法将节点转换为字符串:
XmlDocument doc = new XmlDocument();
doc.Load("''termConditionsExample.xml");
XmlNode node = doc.DocumentElement.SelectSingleNode("/termsAndConditions/logo");
string myString = node.InnerText;
但是,如何对xml文件中的"段落/文本"执行此操作,以将它们转换为List类型呢?我尝试过使用不同的DocumentElement方法,比如下面的一种,但它不起作用:
List<string> paragraphs = new List<string>();
foreach(var temp in doc.DocumentElement.ChildNodes)
{
paragraphs.Add(temp.ToString());
}
我知道这篇文章不接受任何论点,所以是错误的。我只是不知道该用哪一个。。。
我发现LINQ to XML更容易用于类似的事情(例如XDocument
而不是XmlDocument
)。
var xdoc = XDocument.Load("''termConditionsExample.xml");
IEnumerable<string> textValues = xdoc.Descendants("text").Select(e => e.Value);
Xml反序列化也可能是一种合适的方法,正如C.Knight在评论中提到的那样。
您可以使用XmlDocument.SelectNodes
和XmlNode.InnerText
:
foreach (XmlNode node in doc.SelectNodes("/termsAndConditions/paragraphs/text"))
paragraphs.Add(node.InnerText.Trim());
以下是如何将XPath与XDocument
类一起使用:
XDocument document = XDocument.Load(filename);
var result =
document
.XPathSelectElements("termsAndConditions/paragraphs/text")
.Select(x => x.Value.Trim())
.ToList();
它允许您仅选择指定路径中的text
元素(而不是整个xml文件中的所有text
元素)。
确保导入System.Xml.XPath
命名空间,如下所示:
using System.Xml.XPath;