遍历xml以获取元素/节点以更新一个元素

时间:2019-02-07 19:34:33

标签: java mysql xml

因此,我试图从完整XML的字符串值中获取特定的可扣除的xml节点。我正在尝试用变量替换节点内部的字符串,但我没有运气。

下面的代码应该提供我尝试过的内容。

 private String updateXMLDeductible(String Deductible, String xml) {
            try {
                XmlHelper newxml = new XmlHelper();
                Document doc = newxml.loadDoc(xml);
                Node newel = null;

                XPath xpath = new XPath("/location/location/deductible");
                newel = (Node) xpath.selectSingleNode(doc);
                newel.setTextContent(Deductible);
}

我想要的结果是将自付额的字符串值设置为我通过的自付额。

1 个答案:

答案 0 :(得分:1)

我将使用JAXB创建一个反映您的xml模式的对象。解组它。这将返回您的Java对象。更改Java对象中的值。然后根据需要将其封送回字符串(即您的xml)。

例如

@XmlRootElement(name = "YourXMLRootElement") //name is not required if it class name is the same as YourXMLRootElement which I'm assuming is location
@XmlAccessorType(XmlAccessType.FIELD)
public class MyObject{
  public MyObject(){
  /**
    *JAXB requires empty constructor
    */
  }

  @XmlAttribute(name = "deductible")//name is not required if same as attribute name
  private String deductible;
  //getter and setter


  //other attributes with getters and setters
}
private String updateXMLDeductible(String deductible, String xml) {
  MyObject myObject= JAXB.unmarshal(new StringReader(xml), MyObject.class);
  myObject.setDeductible(deductible);
  StringWriter stringWriter = new StringWriter();
  return JAXB.marshal(myObject,stringWriter);
}