解析XML文件
<Datas>
<Item ID="aa" Value="11" />
<Item ID="bb" Value="22" />
<Item ID="cc" Value="33" />
<Table ID="table1" >
<Row>
<Col value="11" />
<Col value="12" />
<Col value="13" />
</Row>
<Row>
<Col value="21" />
<Col value="22" />
<Col value="23" />
</Row>
<Row>
<Col value="31" />
<Col value="32" />
<Col value="33" />
</Row>
</Table>
<Table ID="table2" >
<Row>
<Col value="11" />
<Col value="12" />
<Col value="13" />
</Row>
<Row>
<Col value="21" />
<Col value="22" />
<Col value="23" />
</Row>
<Row>
<Col value="31" />
<Col value="32" />
<Col value="33" />
</Row>
</Table>
</Datas>
解析程序如下:
private void GetDataFromXml(string strXML)
{
try
{
Hashtable itemTable = new Hashtable();
if (strXML == null || strXML.Equals(""))
{
return;
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(strXML);
//解析item
XmlNodeList itemList = doc.GetElementsByTagName("Item");
for (int i = 0; i < itemList.Count; i++)
{
XmlNode node = itemList[i];
XmlAttributeCollection nodeAttributes = node.Attributes;
string strId = nodeAttributes[0].Value;
string strValue = nodeAttributes[1].Value;
itemTable.Add(strId, strValue);
}
//解析Table
XmlNodeList tableList = doc.GetElementsByTagName("Table");
for (int j = 0; j < tableList.Count; j++)
{
XmlNode layer1Node = tableList[j];
string strTableName = layer1Node.Attributes[0].Value;
XmlNodeList layer2NodeList = layer1Node.ChildNodes;
for (int k = 0; k < layer2NodeList.Count; k++)
{
XmlNodeList layer3NodeList = layer2NodeList[k].ChildNodes;
for (int l = 0; l < layer3NodeList.Count; l++)
{
XmlNode layer3Node = layer3NodeList[l];
XmlAttributeCollection layer3NodeAttributeCollection = layer3Node.Attributes;
for (int m = 0; m < layer3NodeAttributeCollection.Count; m++)
{
XmlAttribute layer3NodeAttribute = layer3NodeAttributeCollection[m];
string strLayer3NodeValue = layer3NodeAttribute.Value;
}
}
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
return;
}
}