System.Xml 命名空间
https://msdn.microsoft.com/zh-cn/library/gg145036(v=vs.110).aspx
一、读取
1.通过 XmlDocument获取稳定内容
2.通过XmlNodeList 找到节点数据
private void List_Click(object sender, RoutedEventArgs e)
{
string xmlStr = getData(); StringBuilder rtn = new StringBuilder(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlStr); XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName("root"); foreach (XmlNode xmlNode in xmlNodeList) { //家长节点 XmlNodeList childXmlNodes1 = xmlNode.ChildNodes; foreach (XmlNode childXmlNode1 in childXmlNodes1) { if (childXmlNode1.Name == "resultInfo") { //成员列表 XmlNodeList childXmlNodes2 = childXmlNode1.ChildNodes; foreach (XmlNode childXmlNode2 in childXmlNodes2) { if (childXmlNode2.Name == "NAME") { rtn.Append(childXmlNode2.InnerText); } } } } } }
private string getData() { return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + @" <root> <resultInfo> <NAME>姓名</NAME> <SEX>性别</SEX> <error_msg> 成功!或者error:xxx </error_msg> <remark>备注</remark> </resultInfo> </root> "; }
读取方法扩充
public static LoginResponse GetLoginResponse(string xmlStr) { LoginResponse response = new LoginResponse(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlStr); XmlNode errorNode = xmlDoc.SelectSingleNode("//Error"); if (errorNode != null) { response.ResultErrorCode = (errorNode.SelectSingleNode("ErrorCode")).InnerText; response.ResultErrorText = (errorNode.SelectSingleNode("ErrorText")).InnerText; response.ResultErrorDescription = (errorNode.SelectSingleNode("ErrorDescription")).InnerText; } return response; } 数据: <?xml version="1.0" encoding="UTF-8"?> <RESULT> <Error> <ErrorCode>-1</ErrorCode> <ErrorText>ErrorText</ErrorText> <ErrorDescription>ErrorDescription</ErrorDescription> </Error></RESULT>
二、设置
三、常见问题
1.XmlDocument加载xml文件时,有中文可能会报错,提示配置错误?
因为编码问题造成的,解决方法:
修改XML头部为:<?xml version='1.0' encoding="GB2312"?>