XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<Directory>
<picture>
<add key="0" value="Chrysanthemum.jpg" />
<add key="1" value="Desert.jpg" />
<add key="2" value="Hydrangeas.jpg" />
<add key="3" value="Jellyfish.jpg" />
<add key="4" value="Koala.jpg" />
<add key="5" value="Lighthouse.jpg" />
<add key="6" value="Penguins.jpg" />
<add key="7" value="Tulips.jpg" />
</picture>
<doc>
<add key="0" value="~$1.doc" />
<add key="1" value="~$测试.docx" />
<add key="2" value="测试.docx" />
</doc>
<excel>
<add key="0" value="测试 - 副本 (2).xlsx" />
<add key="1" value="测试 - 副本.xlsx" />
<add key="2" value="测试.xlsx" />
</excel>
<pdf>
<add key="0" value="测试.pdf" />
</pdf>
<ppt>
<add key="0" value="测试.pptx" />
</ppt>
<video>
<add key="0" value="[艾菲]Wake.Up_bd.mp4" />
<add key="1" value="巴啦啦小魔仙.mp4" />
</video>
</Directory>
解析以上XML文件:
public static void ParseXML(string strMsg)
{
print("paeseXML");
print("XML:"+strMsg);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strMsg);//加载XML
XmlNodeList nodeList = xmlDoc.SelectSingleNode("Directory").ChildNodes;
print("NodeNum: " + nodeList.Count);
//遍历每一个节点,拿节点的属性以及节点的内容
foreach (XmlElement xe in nodeList)
{
if (xe.Name == "picture")
{
print("picture count:" + xe.ChildNodes.Count);
for (int m = 0; m < xe.ChildNodes.Count; m++)
{
XmlAttributeCollection attrs = xe.ChildNodes[m].Attributes;
myArray[0, m] = attrs[1].Value;
print("myArray[" + 0 + "][" + m + "]:" + myArray[0, m]);
}
}
if (xe.Name == "doc")
{
print("doc count:" + xe.ChildNodes.Count);
for (int m = 0; m < xe.ChildNodes.Count; m++)
{
XmlAttributeCollection attrs = xe.ChildNodes[m].Attributes;
myArray[1, m] = attrs[1].Value;
print("myArray[" + 1 + "][" + m + "]:" + myArray[1, m]);
}
}
if (xe.Name == "video")
{
print("video count:" + xe.ChildNodes.Count);
for (int m = 0; m < xe.ChildNodes.Count; m++)
{
XmlAttributeCollection attrs = xe.ChildNodes[m].Attributes;
myArray[2, m] = attrs[1].Value;
print("myArray[" + 2 + "][" + m + "]:" + myArray[2, m]);
}
}
if (xe.Name == "ppt")
{
print("ppt count:" + xe.ChildNodes.Count);
for (int m = 0; m < xe.ChildNodes.Count; m++)
{
XmlAttributeCollection attrs = xe.ChildNodes[m].Attributes;
myArray[3, m] = attrs[1].Value;
print("myArray[" + 3 + "][" + m + "]:" + myArray[3, m]);
}
}
if (xe.Name == "excel")
{
print("excel count:" + xe.ChildNodes.Count);
for (int m = 0; m < xe.ChildNodes.Count; m++)
{
XmlAttributeCollection attrs = xe.ChildNodes[m].Attributes;
myArray[4, m] = attrs[1].Value;
print("myArray[" + 4 + "][" + m + "]:" + myArray[4, m]);
}
}
if (xe.Name == "pdf")
{
print("pdf count:" + xe.ChildNodes.Count);
for (int m = 0; m < xe.ChildNodes.Count; m++)
{
XmlAttributeCollection attrs = xe.ChildNodes[m].Attributes;
myArray[5, m] = attrs[1].Value;
print("myArray[" + 5 + "][" + m + "]:" + myArray[5, m]);
}
}
}
print("all = " + xmlDoc.OuterXml);
}
XmlDocument类是.Net API中提供的支持W3C XML DOM标准的类。可以用它来创建和查询XML文档。由于XmlDocument要将XML文档的内容全部装载进内存中,所以对于读取内容过大的XML文档,不适合使用XmlDocument类,而可以使用XmlReader来完成读取。