问答详情
源自:2-3 生成节点间的文本

创建xml文件的缩进与添加相同子节点

写出来xml文件怎么自动缩进啊,不仅仅是换行?还有怎么添加多个book节点啊?

提问者:脚踏地 2015-01-23 17:06

个回答

  • JessicaJiang
    2015-01-24 17:52:37

    缩进可以采用tab键,也可以使用xml专门的编辑器;

    添加多个book节点:

    <bookstore>

        <book>...</book>

        <book>...</book>

        <book>...</book>

        ....

    </bookstore>

  • 脚踏地
    2015-01-27 15:30:29

    //之前之所以添加的book节点会覆盖前面的book节点,是因为变量名都相同,这样的话自然下面的要替换上面的值


    public static void main(String[] args) {
      new TestXml().createXml();
     }
     
     public void createXml(){
      DocumentBuilder db=getDocumentBuilder();
      Document document=db.newDocument();
      document.setXmlStandalone(true);
      Element books=document.createElement("books");
      document.appendChild(books);
      
    //  添加多个节点
      books.appendChild(getChildNode(document,"1","冰与火之歌","乔治马丁","39"));
      books.appendChild(getChildNode(document,"2","安徒生童话","安徒生","29"));
      
      TransformerFactory tff=TransformerFactory.newInstance();
      
      try {
       Transformer tf=tff.newTransformer();
       tf.setOutputProperty(OutputKeys.INDENT, "yes");

    //设置缩进量
       tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
       tf.transform(new DOMSource(document), new StreamResult(new File("lib/books1.xml")));
       
      } catch (TransformerConfigurationException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } catch (TransformerException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
     
     public DocumentBuilder getDocumentBuilder(){
      DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
      DocumentBuilder db = null;
      try {
       db=dbf.newDocumentBuilder();
      } catch (ParserConfigurationException e) {
       e.printStackTrace();
      }
      return db;
     }
     
     public Element getChildNode(Document doc,String id,String name,String author,String price){
      Element childNode=doc.createElement("book");
      childNode.setAttribute("id", id);
      childNode.appendChild(getChildNodeElement(doc,"name",name));
      childNode.appendChild(getChildNodeElement(doc,"author",author));
      childNode.appendChild(getChildNodeElement(doc,"price",price));
      return childNode;
     }

     public Element getChildNodeElement(Document doc,String name,String text){
      Element element=doc.createElement(name);
      element.setTextContent(text);
      return element;
     }