微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.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" 可以识别中文;所以此问题尚未完全解决

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。