.net中XML编程总结

前端之家收集整理的这篇文章主要介绍了.net中XML编程总结前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


一 载入XML文件到树视图

代码

string filepath = Environment.CurrentDirectory + "\\K\\sqlServerZt\\" + "FAMILY2.xml";


try
{
// SECTION 1. Create a DOM Document and load the XML data into it.
XmlDocument dom = new XmlDocument();
dom.Load(filepath);


// SECTION 2. Initialize the TreeView control.
treeView1.Nodes.Clear();
treeView1.Nodes.Add(new TreeNode(dom.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = treeView1.Nodes[0];


//// SECTION 3. Populate the TreeView with the DOM nodes.
AddNode(dom.DocumentElement,tNode);
treeView1.ExpandAll();
}
catch (XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}


private void AddNode(XmlNode inXmlNode,TreeNode inTreeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList nodeList;
int i;


// Loop through the XML nodes until the leaf is reached.
// Add the nodes to the TreeView during the looping process.
if (inXmlNode.HasChildNodes)
{
nodeList = inXmlNode.ChildNodes;
for (i = 0; i <= nodeList.Count - 1; i++)
{
xNode = inXmlNode.ChildNodes[i];
inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = inTreeNode.Nodes[i];
AddNode(xNode,tNode);
}
}
else
{
// Here you need to pull the data from the XmlNode based on the
// type of node,whether attribute values are required,and so forth.
inTreeNode.Text = (inXmlNode.OuterXml).Trim();
}
}


XML文件中都是英文载入正常;



含有中文会出现如下错误提示





正确载入一个含有中文的XML文档到树视图:



该文档如下:

<?xml version="1.0" encoding="gb2312" ?>
<!DOCTYPE 家庭[
<!ELEMENT 家庭 (人+)>
<!ELEMENT 人 EMPTY>
<!ATTLIST 人
relID ID #required
parentID IDREFS #IMPLIED
name CDATA #required
>
]>
<家庭>
<人 relID="P_1" name="爸爸"/>
<人 relID="P_2" name="妈妈"/>
<人 relID="P_3" parentID="P_1 P_2" name="儿子"/>
</家庭>


不过有时用记事本打开该文件,编辑其节点为别的中文内容,保存后再载入又会出错;应该说加了encoding="gb2312" 可以识别中文;所以此问题尚未完全解决

猜你在找的XML相关文章