简体   繁体   English

根据XmlElement上的节点以c#解析XML

[英]Parse XML in c# depending on nodes on XmlElement

I need to parse the following xml : 我需要解析以下xml:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Items>
        <Attr></Attr>
    <Items>
    <Goods>
        <Attr></Attr>
        <Attr></Attr>
        <Attr></Attr>
    </Goods>    
</Response>

This xml is stored on XmlReader output object . 此xml存储在XmlReader output对象上。 Is there any Function to get the first node element Items and store it in an xml element object say xmlelement1 . 是否有任何函数来获取第一个节点元素Items并将其存储在xmlelement1这样的xml元素对象中。 And parse/loop through the xmlelement1 and perform actions. 并解析/循环xmlelement1并执行操作。

Yep, use the XmlDocument: 是的,使用XmlDocument:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("<<PathToXmlFileOnDisk>>");

or if you want to load a string of XML: 或者如果您想加载XML字符串:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<<XmlText>>");

Then go through the thing: 然后经历一下:

foreach(XmlNode node in xmlDoc.SelectSingleNode("./Response").ChildNodes)
{
   ... //Once for each node under Response, then (Ex: Items has its own ChildNodes)
}

If you can use LINQ to XML: 如果可以使用LINQ to XML:

XDocument doc = XDocument.Load(xml);

XElement xelem1 = doc.Root.Element("Items");

foreach (XElement elem in xelem1.Elements())
    Console.WriteLine("Name: {0}, value: {1}", elem.Name, elem.Value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM