C# 将XML文件中的相同元素另存为数组C
这可能是一个愚蠢的问题,但我想问,如何将具有不同内容的.XML文件中的相同元素保存为数组。 XML示例:C# 将XML文件中的相同元素另存为数组C,c#,xml,C#,Xml,这可能是一个愚蠢的问题,但我想问,如何将具有不同内容的.XML文件中的相同元素保存为数组。 XML示例: <ithem> <description>description1</description> <description>description2</description> <description>description3</description> </ithem> 请帮忙 使用LINQ到
<ithem>
<description>description1</description>
<description>description2</description>
<description>description3</description>
</ithem>
请帮忙 使用LINQ到XML将是:
XElement root = XElement.Load(xmlFile);
string[] descriptions = root.Descendants("description").Select(e => e.Value).ToArray();
或
使用XmlDocument解析XML:
var map = new XmlDocument();
map.Load("path_to_xml_file"); // you can also load it directly from a string
var descriptions = new List<string>();
var nodes = map.DocumentElement.SelectNodes("ithem/description");
foreach (XmlNode node in nodes)
{
var description = Convert.ToString(node.Value);
descriptions.Add(description);
}
您已经描述了任务,但问题到底是什么?当您实现它时,您已经走了多远,任务的哪一部分构成了障碍?读取Xml文件?找到价值观?编写数组?您使用哪种xml技术?无论如何无论您使用什么,都应该以某种形式支持XPath,并且您需要类似doc.SelectNodes/ithem/description的内容来获取描述字段的节点列表。然后可以使用它来创建数组。
string[] descriptions = root.Element("ithem").Elements("description").Select(e => e.Value).ToArray();
var map = new XmlDocument();
map.Load("path_to_xml_file"); // you can also load it directly from a string
var descriptions = new List<string>();
var nodes = map.DocumentElement.SelectNodes("ithem/description");
foreach (XmlNode node in nodes)
{
var description = Convert.ToString(node.Value);
descriptions.Add(description);
}
descriptions.ToArray();