0

I am trying to insert string value in an xml file , but I am not getting exactly how to insert using java.

textFieldChoose.setText(fileChooser.getSelectedFile().toString());

                    String str="";

                  final JFrame msgframe= new JFrame();
                  msgframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                  str= textFieldChoose.getText();
                  JOptionPane.showMessageDialog(textFieldChoose, str);
                  ClassLoader classLoader = getClass().getClassLoader();
                  str= textFieldChoose.getText();

I can store the value in a string. I need to replace that value every time when whenever my application will pick another value in the string.

xml:-

?xml version="1.0" encoding="UTF-8"?>

<project name="org.world.rg" default="rg.init" basedir=".">

  <property name="dita.dir" location="${basedir}/../../.."/>

  <target name="rg.init" description="build PDF" depends="pdf"/>


  <target name="pdf" description="build PDF">
    <ant antfile="${dita.dir}/build.xml">
      <property name="args.input" location=""/>

I need to insert that string value in location =""/> . what are the possible ways?

Jobin
  • 5,610
  • 5
  • 38
  • 53
Rohit Ghosh
  • 53
  • 11

2 Answers2

0

You can use an XPATH expression to update this element:

//project/target/ant/property ...

How to read XML using XPath in Java

Community
  • 1
  • 1
itstata
  • 1,058
  • 7
  • 17
  • I am using this `XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/project/target[1]/ant/property/@location"; Node node = (Node) xPath.evaluate(expression, document, XPathConstants.NODE); node.setTextContent(str);` but facing exceptions . Can you instruct correct way to follow tags according to my xml. – Rohit Ghosh Jan 18 '17 at 07:35
  • The location attribute must be in brackets: //Parent[@id='1']/Children/child[@location] – itstata Jan 18 '17 at 07:40
  • Throwing lots of exceptions – Rohit Ghosh Jan 20 '17 at 04:51
0

A simple way with java 8 API Files, but I do not think it's the best, it would be:

1) Read file 2) replace value 3) write file

byte[] fileContent = Files.readAllBytes(Paths.get("example.xml"));
String content = new String(fileContent)
                    .replace("location =\"\"", "location =\"" + str + "\"");
Files.write(Paths.get("example.xml"), xmlString.getBytes());