Java Dom XML

public void readFile(String fileName){
        SAXReader reader = new SAXReader();
        reader.setEncoding("UTF-8");
        try{
            Document  doc1 = reader.read(new File("C:\\Users\\jiming\\Desktop\\cde5adb2-6830-3e2f-b818-5591edea0d5f\\map_gohome_branch.xml"));
            Element root1 = doc1.getRootElement();
            List nodes1 = root1.elements("map_gohome_branch");
            Iterator it1 = nodes1.iterator();
            while (it1.hasNext()) {//Listing
Element elm1 = (Element) it1.next();
Iterator<Element> atr1 = elm1.elementIterator();
while (atr1.hasNext()) {// Elemnt
Element ee = (Element) atr1.next();
if (ee.getName().equals("name_chi")) {
System.out.println(ee.getStringValue());
}
if (ee.getName().equals("Amenity")) {
List<Attribute> attributes = ee.attributes();
if (attributes != null && attributes.size() > 0) {
for(int i=0;i<attributes.size();i++) {
                       if(attributes.get(i).getText().equals("1")){
                       System.out.println(attributes.get(i).getValue());
                       }else if(attributes.get(i).getText().equals("2")){
                       System.out.println(attributes.get(i).getValue());
                        }
}
}
}
}
            }
        }catch(Exception e){
        e.printStackTrace();
        }
}
public void writeFile(String fileName){
try{
Document document = DocumentHelper.createDocument();
Element Lists = document.addElement("Lists");
for(int i=0;i<10;i++){
Element Listing = Lists.addElement("Listing");
Element LastUploadDate = Listing.addElement("LastUploadDate");
LastUploadDate.setText("2013-12-12");
Element Photos = Listing.addElement("Photos");
for(int j=0;j<6;j++){
Photos.addAttribute("path",j+"");
}
}
FileOutputStream fos = new FileOutputStream("simple.xml");
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(fos, format);
writer.write(document);
writer.flush();
}catch(Exception e){
e.printStackTrace();
}
}

你可能感兴趣的:(JAVA DOM4J XML)