您的位置:首页 > 其它

关于XML解析的几个实用方法

2007-07-15 16:30 435 查看
1 获取XML文件的路径


protected static String ServerRoot()




...{


return HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath).TrimEnd('/');


}



2 将XML中的所有节点用一定规则将所有的节点组装成一个String,可以在不同节点元素之间加入一个符号. 便于以后处理的时候用split()方法处理,放入一个数组里面,这样操作XML各个节点就变换成操作一个数组了。


private static String ShowXML(XmlNodeList nodeList)




...{


String strReturn = "";




foreach (XmlNode node in nodeList)




...{


if (node.NodeType != XmlNodeType.Comment)




...{


if (node.HasChildNodes)




...{


foreach (XmlNode nn in node.ChildNodes)




...{


strReturn += nn.InnerText;




strReturn += "*";


}


}




//strReturn = strReturn.Substring(0, strReturn.Length - 1);




//不同节点之间


strReturn += "?";


}


}




strReturn = strReturn.Substring(0, strReturn.Length - 1);




return strReturn;


}

3


// 指定XML文件路径,获得节点值


private static String GetByPath(String strPath, String strKey)




...{


XmlDocument xDoc = null;


String strReturn = "";




try




...{




xDoc = new XmlDocument();




xDoc.Load(strPath);




XmlElement xElem = (XmlElement)(xDoc.SelectSingleNode(strKey));




if (xElem != null)




...{


String str = xElem.InnerText.Replace(" ", "");




strReturn = str.Trim();


}


}


catch (Exception e)




...{


String str = e.Message;




strReturn = "";


}




finally




...{


xDoc = null;


}




return strReturn;


}

4


// 指定路径,获得指定节点及其所有子节点的值(暂时用于Style的读取)


private static String GetAllByPath(String strPath, String strKey)




...{


XmlDocument xDoc = null;


String strReturn = "";




try




...{


xDoc = new XmlDocument();




xDoc.Load(strPath);




XmlElement xElem = (XmlElement)(xDoc.SelectSingleNode(strKey));




if (xElem != null)




...{


XmlNodeList nodeList = xElem.ChildNodes;




strReturn = ShowXML(nodeList);


}


}


catch (Exception e)




...{


String str = e.Message;


}




return strReturn;


}

指定XML文件路径,获得节点值. 每次获得单独的一个节点值,所以也不需要什么规则来组装一个string。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: