在开发中,每当遇到数据交流时,总免不了要进行数据的处理,而xml的解析就变的司空见惯,同时也很重要,所以必须要学会基础的xml解析。
如下有一xml文件 内容:
<?xml version="1.0" encoding="GBK"?>
<root>
<player haha="welcom" ll="dfdfd">
<id> 11</id>
<name>45</name>
</player>
<player haha="566" ll="fasdf">
<id>1122 </id>
<name>4sdfssda5</name>
</player>
<player haha="weicome" ll="qwert">
<id> 111</id>
<name>4dsf5</name>
</player>
</root>
这是很单一的一种,比较简单。先从简单的入手吧!用java写了一个类。如下:
解析类
public class MyDomXML {
public static void main(String[] arges){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Document result = parser.parse(binaryStream);
DocumentBuilder builder = null;
try{
builder=factory.newDocumentBuilder();
}catch(ParserConfigurationException e){
e.printStackTrace();
}
Document doc = null;
try{
doc = builder.parse("D:"+File.separator+"x.xml");
}catch(SAXException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
NodeList nl = doc.getElementsByTagName("player");
for(int i=0;i<nl.getLength();i++){
Element e = (Element)nl.item(i);
System.out.println(e.getAttribute("haha"));
System.out.println(e.getAttribute("ll"));
// System.out.println("\n");
System.out.println("ndd"+e.getElementsByTagName("id").item(0).getFirstChild().getNodeValue());
System.out.println("id"+e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
System.out.println("\n");
}
}
}
结果为:
在C#中曾遇到解析xml,当时只需要解析出第一个节点的内容便可以, 因此便用了一中简单的方法实现,函数如下:
public string xmlWrite(string args){
// string ss = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
string idell = null;
string rec ="<root>" + args + "</root>";
// rec += Encoding.UTF8.GetString(bytesRevStr, 0, bytes);
// XmlDocument xmlDoc = new XmlDocument();
// System.Xml.XmlDocument DOM = new System.Xml.XmlDocument();
System.IO.StringReader xmlSR = new System.IO.StringReader(rec);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rec);
XmlNodeList nodelist = xmlDoc.SelectSingleNode("root").ChildNodes;
XmlNode root = xmlDoc.DocumentElement;
foreach (XmlNode xn in nodelist)
{
XmlElement xe = (XmlElement)xn;
idell = xe.GetAttribute("id");
}
return idell;
}
其中args为从数据库中获取的xml 内容为<account id="111"/><account id="112"/>
rec 则为一个完整的xml文档。 结果为idell=111.
只取xml中的第一个节点内容只能算是一个特例。接下来,写一个范例,用于解析xml并将解析的内容放入数组中保存。代码:
int[] aid = new int[htnum];
string rec = "<root>" + newxml + "</root>";
System.IO.StringReader xmlSR = new System.IO.StringReader(rec);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rec);
//XmlNodeList nodelist = xmlDoc.SelectSingleNode("root").ChildNodes;
XmlNodeList nodelist = xmlDoc.GetElementsByTagName("account");
//XmlNode root = xmlDoc.DocumentElement;
for (int n = 0; n < nodelist.Count; n++)
{
XmlElement xe = (XmlElement)nodelist.Item(n);
otherid = int.Parse(xe.GetAttribute("id"));
aid[n] = otherid;
}
newxml 同上。这些只是简单的xml的解析,复杂的原理相同,只是工序多一点。谨慎对待就OK了!