[英]How to read child nodes from XML without knowing their names using C#?
I apologize if this was asked before. 如果这是以前问过的,我深表歉意。 (I'm just learning this.)
(我只是在学习这个。)
Say, I have the following XML: 说,我有以下XML:
<Row>
<c0>1</c0>
<c1>31b64f1cb075</c1>
<c2>Developer</c2>
<c3/>
<c4/>
<c5/>
<c6/>
<c7/>
<c8>USA</c8>
<c9>http://www.microsoft.com</c9>
<c10>sales@microsoft.com</c10>
<c11/>
<c12/>
<c13/>
<c14>-2147483648</c14>
<c15>2012-03-08T09:55:42-08:00</c15>
<c16>00000000-0000-0000-0000-000000000000</c16>
<c17>587312C</c17>
</Row>
Say, I get to the "row" element by using: 说,我通过使用以下命令进入“行”元素:
//xmlReader is of type XmlReader
xmlReader.ReadToFollowing("Row");
But how do I collect all "c*" child elements not knowing their names and how many of them are there? 但是,如何收集所有不知道其名称的“ c *”子元素以及它们中有多少个呢?
You can also use an XmlDocument to load your xml and simply loop through the childnodes like this 您还可以使用XmlDocument加载xml并像这样简单地遍历子节点
XmlDocument doc = new XmlDocument();
doc.LoadXml("yourxml");
XmlNode root = doc.FirstChild;
//Display the contents of the child nodes.
if (root.HasChildNodes)
{
for (int i=0; i<root.ChildNodes.Count; i++)
{
Console.WriteLine(root.ChildNodes[i].InnerText);
}
}
You can read more about it here http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.childnodes.aspx 您可以在这里阅读更多有关它的信息http://msdn.microsoft.com/zh-cn/library/system.xml.xmlnode.childnodes.aspx
Hope it helps! 希望能帮助到你!
Using Linq to XML you could just use Elements()
to get all the direct children (or use Descendants
for any descendant): 使用Linq到XML,您可以只使用
Elements()
来获取所有直接子代(或对任何子代使用Descendants
):
XElement root = XElement.Load("test.xml"); //contains your xml
foreach (var child in root.Elements())
{
Console.WriteLine(child.Name);
}
Try this 尝试这个
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.Load(@"test.xml");//loading XML in xml doc
if (xdoc.ChildNodes.Count > 0)
{
XmlNodeList xm = xdoc.DocumentElement.ChildNodes;
// In this loop you have get all the child control
foreach (XmlNode x in xm)
{
string data= x.InnerXml;
}
}
var xml="<Row>...</Row>"
var xmlReader = XmlReader.Create(new StringReader(xml));
if (xmlReader.ReadToFollowing("Row"))
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
var name = xmlReader.Name;
//read value of element.
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Whitespace)
break;
if (xmlReader.NodeType == XmlNodeType.Text)
{
var value = xmlReader.Value;
}
else if (xmlReader.NodeType == XmlNodeType.EndElement)
break;
}
}
}
}
this code can worked. 此代码可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.