XML是作为一种通用的数据格式语言,可以在不同的平台,不同语言之间作为存储数据,进行信息交换。
因为在项目中使用,讲解下java是如何对XML文件或者字符串进行解析,利用dom4j工具包:
首先下载dom4j工具包,并配置到Web项目中;
对下边XML字符串进行解析
解析代码:
public class TestUserInfo { public static void main(String[] args) throws Exception { String person = "<Result><Value>0</Value><Person Name='yuchen' CardNumber='123456' Address='china'/></Result>"; SAXReader reader = new SAXReader(); Document document = reader.read(new InputSource(new StringReader(person))); //获取XML文档的根元素 Element elementResult = document.getRootElement(); //获取根元素下的所有一级子元素 List<Element> firstSubElements = elementResult.elements(); //获取Value子元素 Element elementValue = firstSubElements.get(0); String value = elementValue.getText(); //获取Person子元素及其属性 Element elementPerson = firstSubElements.get(1); String name =elementPerson.attributeValue("Name"); String cardNumber = elementPerson.attributeValue("CardNumber"); String address=elementPerson.attributeValue("Address"); System.out.println("Value: "+value); System.out.println("Person: Name="+name+" CardNumber="+cardNumber+" Address="+address); } }
Value: 0
Person: Name=yuchen CardNumber=123456 Address=china
如果是解析XML文件,同样是需要得到Document对象,file为文件地址字符串
//根据文件名创建Document对象 SAXReader reader = new SAXReader(); Document document = reader.read(new File(file));
那么如果生成一个person的字符串,是如何生成呢?代码如下
public static void main(String[] args) throws Exception { //创建Document对象 Document document = DocumentHelper.createDocument(); //创建根节点 Element elementResult = DocumentHelper.createElement("Result"); document.setRootElement(elementResult); //给根节点添加子节点Value Element elementValue = elementResult.addElement("Value"); elementValue.setText("0"); //给根节点添加子节点Value Element elementPerson = elementResult.addElement("Person"); elementPerson.addAttribute("Name", "yuchen").addAttribute("CardNumber", "123456").addAttribute("Address", "china"); //输出格式化器 OutputFormat format = new OutputFormat(" ", true); //设置编码 format.setEncoding("utf-8"); format.setSuppressDeclaration(true); //xml输出器 StringWriter out = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(out, format); //打印doc try { xmlWriter.write(document); xmlWriter.flush(); } catch (IOException e) { e.printStackTrace(); } //关闭输出器的流,即是printWriter String person = out.toString(); System.out.println(person); }
format.setSuppressDeclaration(true);如果设为false,则会出现XML声明 <?xml version="1.0" encoding="utf-8"?>
<Result>
<Value>0</Value>
<Person Name="yuchen" CardNumber="123456" Address="china"/>
</Result>