I have an xml like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<User SOURCE_NAME="PublicAssetFeed" xmlns="http://abc.e.wat.com/xml">
<Employee>
<FIELD NAME="Name" TYPE="char">Rahul</FIELD>
<FIELD NAME="Branch" TYPE="char"></FIELD>
<FIELD NAME="Unique ID" TYPE="char">12345</FIELD>
</Employee> `
I want to delete the entire line where NAME="Branch". So my final XML should look like
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<User SOURCE_NAME="PublicAssetFeed" xmlns="http://abc.e.wat.com/xml">
<Employee>
<FIELD NAME="Name" TYPE="char">Rahul</FIELD>
<FIELD NAME="Unique ID" TYPE="char">12345</FIELD>
</Employee>
</User>`
I need to do this using Java. Above XML is stored as a String. So, I need to convert it to XML, delete the particular line and then convert back to String. I tried using XPath and I could only find the main node which is 'FIELD' using the below Java code. How do I delete the entire line where NAME="Branch"
package com.javamultiplex;
import java.io.IOException;
import java.io.StringReader;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class test {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException{
String abc="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><User SOURCE_NAME=\"PublicAssetFeed\" xmlns=\"http://abc.e.wat.com/xml\"><Employee><FIELD NAME=\"Name\" TYPE=\"char\">Rahul</FIELD><FIELD NAME=\"Unique ID\" TYPE=\"char\">12345</FIELD><FIELD NAME=\"Branch\" TYPE=\"char\"></FIELD></Employee></User>"
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
XPath xPath = XPathFactory.newInstance().newXPath();
InputSource sourceMasterTitle = new InputSource(new StringReader(abc.toString()));
String expression = "//FIELD[@NAME='Branch']";;
Node value = (Node) xPath.evaluate(expression, sourceMasterTitle ,XPathConstants.NODE);
System.out.println("Main node is "+value.getNodeName());
}
}