1.sax dom dom4j 去解析一个xml
要求的xml
<?xml version="1.0" encoding="utf-8"?>
<!--这是一个神奇的宇宙 -->
<human>
<person num="0001">
<name>卢凯奇</name>
<age>18</age>
<work>学生</work>
<skill>无敌</skill>
<desc>永远年轻,human宇宙001号选手</desc>
</person>
<person num="0002">
<name>白展堂</name>
<age>18</age>
<work>跑堂的</work>
<skill>葵花点穴手</skill>
<desc>盗圣</desc>
</person>
<person num="0003">
<name>佟湘玉</name>
<age>18</age>
<work>展柜的</work>
<skill>移魂大法</skill>
<desc>曾经的什么什么堂堂主</desc>
</person>
<person num="0004">
<name>李大嘴</name>
<age>18</age>
<work>烧菜的</work>
<skill>降龙十巴掌</skill>
<desc>做的饭很咸,师傅是御膳房总管,先帝是被他师傅活活齁死的</desc>
</person>
</human>
1.1 sax代码
@Test
public void SAXtest() throws Exception {
// 工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
// 解析器
SAXParser newSAXParser = factory.newSAXParser();
newSAXParser.parse("src/person.xml", new DefaultHandler() {
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
System.out.println("开始解析");
System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
System.out.print("<" + qName);
for (int i = 0; i < attributes.getLength(); i++) {
System.out.print(" "+attributes.getQName(i) + "=\"" + attributes.getValue(i) + "\">");
}
if (attributes.getLength() == 0)
{
System.out.print(">");
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String str= new String(ch,start,length);
System.out.print(str);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("/<"+qName+">");
}
@Override
public void endDocument() throws SAXException {
System.out.println("结束解析");
}
});
1.2 dom 代码
@Test
public void domAnalysis() throws Exception {
DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
DocumentBuilder newDocumentBuilder = Factory.newDocumentBuilder();
// 文档对象 用来表示被解析的xml
Document document = newDocumentBuilder.parse(new File("src/person.xml"));
System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
print(document);
}
//都继承了node
public void print(Node node) {
if (node == null) {
System.out.println("节点为空");
}
switch (node.getNodeType()) {
case Node.DOCUMENT_NODE:
// 先把node 转回来
Document document = (Document) node;
// 获得根节点
Element element = document.getDocumentElement();
print(element);
break;
case Node.ELEMENT_NODE:
Element childElement = (Element) node;
System.out.print("<" + childElement.getTagName());
NamedNodeMap attributes = childElement.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
print(attributes.item(i));
}
if(attributes.getLength()==0) {
System.out.print(">");
}
// 子节点
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
print(childNodes.item(i));
}
System.out.print("</" + childElement.getTagName() + ">");
break;
case Node.TEXT_NODE:
System.out.print(node.getTextContent());
break;
case Node.ATTRIBUTE_NODE:
Attr attr = (Attr) node;
System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\">");
break;
case Node.COMMENT_NODE:
System.out.println("-------------------------");
break;
default:
throw new RuntimeException("解析到意外的节点");
}
}
1.3 dom4j代码
@Test
public void Dom4j() throws Exception {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("src/cd.xml");
//根标签
Element element = document.getRootElement();
//根标签的子标签
List<Element> list = element.elements();
list.forEach((t)->{
//标签名
System.out.print(" "+"<"+t.getName());
List<Attribute> list2 = t.attributes();
list2.forEach((p)->{
//属性
System.out.println(" "+p.getName()+"=\""+p.getValue()+"\">");
});
List<Element> list3 = t.elements();
// System.out.println("------------------------------");
// System.out.println(list3.get(0).getName()+list3.get(0).getText());
// System.out.println("-------------------------------");
list3.forEach(l->{
//获取不带空格的文本
// System.out.println(l.getTextTrim());
System.out.print("\t"+"<"+l.getName()+">");
System.out.print(l.getText());
System.out.println("<"+l.getName()+">");
});
System.out.println("</"+t.getName()+">");
});
}
2.dom4j去构建家族的xml
要求的xml
<ancestors>
<father id="1234567890">
<name>李四</name>
<salary>1231.11</salary>
<father>
<son id="ssss">
<name>李四1</name>
<salary>1221.11</salary>
<son>
</ancestors>
2.1代码
public static void main(String[] args) throws Exception {
Document document = DocumentHelper.createDocument();
// 等到一个根节点
Element element = document.addElement("ancestors");
Element attribute = element.addElement("father").addAttribute("id", "1234567890");
attribute.addElement("name").addText("tom");
attribute.addElement("salary").addText("2000");
Element attribute2 = element.addElement("son").addAttribute("id", "1234567891");
attribute2.addElement("naem").addText("sala");
attribute2.addElement("salary").addText("2100");
OutputFormat format = new OutputFormat();
//编码
format.setEncoding("utf-8");
//换行
format.setNewlines(true);
//缩进
format.setIndent(true);
//打印出去
XMLWriter writer = new XMLWriter(new PrintWriter("src/work2.xml"),format);
//把根节点写进去
writer.write(document);
writer.flush();
writer.close();
}
3.将cd.xml封装对象,并且将所有的对象存储起来到一个文件
要求的xml
<?xml version="1.0" encoding="UTF-8"?>
<cds>
<cd id="x112">
<name>周杰伦</name>
<price>155.5</price>
<title>七里香</title>
</cd>
<cd id="x113">
<name>林俊杰</name>
<price>156.1</price>
<title>江南</title>
</cd>
<cd id="x114">
<name>蔡依林</name>
<price>155.65</price>
<title>呸</title>
</cd>
<cd id="x115">
<name>蔡徐坤</name>
<price>15.61</price>
<title>篮球</title>
</cd>
<cd id="x116">
<name>毛不易</name>
<price>156.1</price>
<title>入海</title>
</cd>
</cds>
3.1代码
public static void main(String[] args) throws Exception {
SAXReader saxReader = new SAXReader();
Document read = saxReader.read("src/cd.xml");
//根节点
Element element = read.getRootElement();
//根节点的子节点
List<Element> elements = element.elements();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/cd.txt"));
elements.forEach(t->{
Person person = new Person();
List<Attribute> attributes = t.attributes();
attributes.forEach(p->{
person.setId(p.getValue());
});
List<Element> list = t.elements();
person.setName(list.get(0).getText());
person.setPrice(list.get(1).getText());
person.setTitle(list.get(2).getText());
try {
oos.writeObject(person);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}
});
oos.close();
}