在foreach循环中通过标记读取xml 示例xml:
<users>
<user>
<id>12345567</id>
<name>Ronsna Stedinberg</name>
</user>
<user>
<id>12345568</id>
<name>Sonsna Dtedinberg</name>
</user>
</users>
现在我想将标签保存到包含所有子标签的新文件
答案 0 :(得分:1)
这是循环用户节点的方式
string xml = @"<users><user><id>12345567</id><name>Ronsna Stedinberg</name></user><user><id>12345568</id><name>Sonsna Dtedinberg</name></user></users>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList nodeList = doc.SelectNodes("//users/user");
foreach (XmlNode node in nodeList)
{
string id = node.SelectSingleNode("id").InnerText;
string name = node.SelectSingleNode("name").InnerText;
}
答案 1 :(得分:1)
Linq to XML方法:
// Assuming your xml is named data.xml
XDocument xml = XDocument.Load("data.xml");
var tags = from x in xml.Descendants("user")
select new
{
id = x.Element("id").Value,
name = x.Element("name").Value
};
foreach (var tag in tags)
{
Console.WriteLine(tag.id);
Console.WriteLine(tag.name);
}