Created
March 29, 2017 02:58
-
-
Save pvlasov/1a2670c0bed2a398544fb59f9261d174 to your computer and use it in GitHub Desktop.
Short summary of XML processing - parse, manipulate, output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import javax.xml.parsers.DocumentBuilder; | |
import javax.xml.parsers.DocumentBuilderFactory; | |
import javax.xml.transform.OutputKeys; | |
import javax.xml.transform.Transformer; | |
import javax.xml.transform.TransformerFactory; | |
import javax.xml.transform.dom.DOMSource; | |
import javax.xml.transform.stream.StreamResult; | |
import javax.xml.xpath.XPath; | |
import javax.xml.xpath.XPathConstants; | |
import javax.xml.xpath.XPathExpression; | |
import javax.xml.xpath.XPathFactory; | |
import org.w3c.dom.Document; | |
import org.w3c.dom.Element; | |
import org.w3c.dom.NodeList; | |
public class ... { | |
public static void main(String argv[]) throws Exception { | |
File fXmlFile = new File(...); | |
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); | |
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); | |
Document doc = dBuilder.parse(fXmlFile); | |
// optional, but recommended | |
// read this - | |
// http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work | |
doc.getDocumentElement().normalize(); | |
XPathFactory xPathfactory = XPathFactory.newInstance(); | |
XPath xpath = xPathfactory.newXPath(); | |
XPathExpression expr = xpath.compile("/plugin/extension[@point='org.nasdanika.cdo.web.renderer']/renderer"); | |
NodeList result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); | |
System.out.println(result); | |
for (int i = 0; i < result.getLength(); ++i) { | |
Element eObjectRoute = (Element) result.item(i); | |
eObjectRoute.setAttribute("renderer", "some attribute"); | |
} | |
XPathExpression textExtExpr = xpath.compile("/plugin/extension[@point='org.nasdanika.cdo.web.test']"); | |
Element testExt = (Element) textExtExpr.evaluate(doc, XPathConstants.NODE); | |
if (testExt == null) { | |
testExt = doc.createElement("extension"); | |
testExt.setAttribute("point", "org.nasdanika.cdo.web.test"); | |
((Element) xpath.compile("/plugin").evaluate(doc, XPathConstants.NODE)).appendChild(testExt); | |
} | |
//doc.importNode(node, true); | |
// Use a Transformer for output | |
TransformerFactory tFactory = TransformerFactory.newInstance(); | |
Transformer transformer = tFactory.newTransformer(); | |
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); | |
DOMSource source = new DOMSource(doc); | |
StreamResult out = new StreamResult(System.out); | |
transformer.transform(source, out); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment