简体   繁体   中英

Modify XML file at specific node

I have an xml like this

<list>
<job>
    <id>B001</id>
    <name>Job1</name>
    <time>7</time>
    <status>success</status>
</job>
<job>
    <id>B002</id>
    <name>Job2</name>
    <time>1</time>
    <status>success</status>
</job>

I want to change the at specific job with a specific name. I did some search on google but it's no help.Anyone know a good way to do this in Java? Or a doc will also be appreciated. I wonder a method which might be changeTimeOfJob(String id, int time)

Try using jsoup

public String changeTimeOfJob(String id, int time){
    Document doc = Jsoup.parse(input, "", Parser.xmlParser());
    String selection = "job > id:contains("+id+")";
    Element resultLinks = doc.select(selection).first();
    resultLinks.parent().select("time").first().text(String.valueOf(time));
    return doc.html(); // Gives you the resulting XML you can write back to file
}

If you have the xml as String, use:

String html = "<YOURXML>";
Document doc = Jsoup.parse(html);

Look in https://jsoup.org/cookbook/extracting-data/selector-syntax for further information.

Edit: Put in the selector for you. Edit2: Updated full code

Edit3: I actually tested it now, there were some errors before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM