reading xml by tag in a foreach loop example xml:
<users>
<user>
<id>12345567</id>
<na开发者_如何学编程me>Ronsna Stedinberg</name>
</user>
<user>
<id>12345568</id>
<name>Sonsna Dtedinberg</name>
</user>
</users>
now i would like to save a tag to a new file with all its sub tags
This is how you would loop the user nodes
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;
}
A Linq to XML approach:
// 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);
}
精彩评论