0

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)

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to overwrite the element at a specific node, not to parse the file
Once you found the element you can set the attribute and put it back to a file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.