开发者

reading xml by tag and writing

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);
}                        
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜