how to insert value into xml?

谁都会走 提交于 2019-12-23 03:17:06

问题


I am really new to XML and JDOM so I have a noob question, sorry for that. I have a XML file and I want to insert value into it. My XML file is like that;

<?xml version="1.0"?>
<message>
    <header>
        <messageType>  </messageType>
        <sendFrom> </sendFrom>
        <HostName> </HostName>
        <sendTo> </sendTo>
        <receiverName> </receiverName>
        <date> </date>
    </header>
    <body>
    </body>
</message>

So what I want is for example is to add value between <sendTo> </sendTo> and also I want to add <A> data </A> between <body> </body>. Can you please tell me how to do that ?

Thanks a lot.


回答1:


http://www.cafeconleche.org/books/xmljava/chapters/ch14s04.html

http://www.java2s.com/Code/Java/XML/MakeupandwriteanXMLdocumentusingDOM.htm




回答2:


If you use dom,you can do it as follows;

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(inputFile);

        Node messageType= doc.getElementsByTagName("messageType").item(0);//zero tells the order in the xml
        messageType.setTextContent("SMS");



回答3:


I'd recommend using XStream for XML handling. Here, is the link to a 2 minute tutorial: http://x-stream.github.io/tutorial.html



来源:https://stackoverflow.com/questions/7610894/how-to-insert-value-into-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!