Where The Streets Have No Name

JDom - 기존 xml파일에 내용 추가 본문

Developement/Java

JDom - 기존 xml파일에 내용 추가

highheat 2010. 4. 6. 15:29
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;

public class CdrXmlDemo4 {

    public static void main(String[] args) {
        try {
            SAXBuilder b = new SAXBuilder();  // true -> validate

            // Create a JDOM document.
            Document doc = b.build(new File("msc.xml"));

            XPath xpath = XPath.newInstance("//cdr/message/message-id");
            List list = xpath.selectNodes(doc);
            int cnt = 1;
            for (Iterator iter = list.iterator(); iter.hasNext();) {
                Element elem = (Element) iter.next(); 
                System.out.println(elem.getName() + " ," + elem.getText());

                if(elem.getTextTrim().equals("123456")){
                    XPath xpath2 = XPath.newInstance("//cdr/message["+cnt+"]/msc/pdu-data");
                    Element pduData = (Element)xpath2.selectSingleNode(doc);
                    Element pduKey = new Element("pdu-key");
                    pduKey.setText("pdu key");
                    pduData.addContent(pduKey);
                    Element pduValue = new Element("pdu-value");
                    pduKey.setText("pdu key");
                    pduData.addContent(pduValue);
                    pduKey.setText("pdu value");
                }
                cnt++;
            }

            // Create an output formatter, and have it write the doc.
            FileOutputStream out = new FileOutputStream("msc.xml");
            XMLOutputter serializer = new XMLOutputter();

            Format f = serializer.getFormat();
            f.setEncoding("UTF-8");
            f.setIndent(" ");
            f.setLineSeparator("\r\n");
            f.setTextMode(Format.TextMode.TRIM);
            serializer.setFormat(f);

            serializer.output(doc, out);
            out.flush();
            out.close();

        } catch (JDOMException jex) {
            System.out.print("PARSE ERROR: " + jex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
jdom에서 xpath를 사용하기 위해서는 jaxen을 같이 설치해야함