Java Code Examples for javax.xml.xpath.XPathExpression#evaluate()

The following examples show how to use javax.xml.xpath.XPathExpression#evaluate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CrossGatewayQueryTest.java    From openxds with Apache License 2.0 6 votes vote down vote up
private NodeList getElementValue(OMElement response, String type, String element, String value)throws ParserConfigurationException, IOException, SAXException, XPathExpressionException{
		
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
	    domFactory.setNamespaceAware(false); // never forget this!
	    DocumentBuilder builder = domFactory.newDocumentBuilder();
	    Document doc = builder.parse(new StringInputStream(response.toString()));
	    
		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		XPathExpression expr = null;
		if (type.equalsIgnoreCase("ExtrinsicObject"))
			expr = xpath.compile("//AdhocQueryResponse/RegistryObjectList/ExtrinsicObject[@"+element+"='"+value+"']"); 
		if (type.equalsIgnoreCase("ExternalIdentifier"))
			expr = xpath.compile("//AdhocQueryResponse/RegistryObjectList/ExtrinsicObject/ExternalIdentifier[@"+element+"='"+value+"']"); 
		Object res = expr.evaluate(doc, XPathConstants.NODESET);
	    NodeList nodes = (NodeList) res;
		return nodes;
}
 
Example 2
Source File: WSDL11SOAPOperationExtractor.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private Node findFirstElementByName(String name, Document doc) {
    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();
    try {
        XPathExpression expr = xpath.compile("//*[@name='" + name + "']");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        if (nodes == null || nodes.getLength() < 1) {
            return null;
        }
        return nodes.item(0);
    } catch (XPathExpressionException e) {
        log.error("Error occurred while finding element " + name + "in given document", e);
        return null;
    }
}
 
Example 3
Source File: ProPresenterParser.java    From Quelea with GNU General Public License v3.0 6 votes vote down vote up
private Optional<String> getSectionTextLegacy(Node slideNode) {
	try {
		XPathFactory xPathfactory = XPathFactory.newInstance();
		StringBuilder ret = new StringBuilder();
		XPathExpression expr = xPathfactory.newXPath().compile(".//RVTextElement");
		NodeList lines = (NodeList) expr.evaluate(slideNode, XPathConstants.NODESET);
		LOGGER.log(Level.INFO, "Found {0} lines", lines.getLength());
		for (int j = 0; j < lines.getLength(); j++) {
			Node lineNode = lines.item(j);
			String line = new String(Base64.getDecoder().decode(lineNode.getAttributes().getNamedItem("RTFData").getTextContent()), Charset.forName("UTF-8"));
			line = stripRtfTags(line).trim();
			ret.append(line).append('\n');
		}
		return Optional.of(ret.toString());
	} catch (XPathExpressionException | DOMException ex) {
		LOGGER.log(Level.SEVERE, "Error with import legacy", ex);
		return Optional.empty();
	}
}
 
Example 4
Source File: XMLHelpers.java    From SAMLRaider with MIT License 6 votes vote down vote up
/**
 * Set the ID Attribute in an XML Document so that java recognises the ID
 * Attribute as a real id
 *
 * @param document
 *            Document to set the ids
 */
public void setIDAttribute(Document document) {
	try {
		if(Thread.currentThread().getContextClassLoader() == null){
			Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); 
		}
		XPath xpath = XPathFactory.newInstance().newXPath();
		XPathExpression expr = xpath.compile("//*[@ID]");
		NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element elem = (Element) nodeList.item(i);
			Attr attr = (Attr) elem.getAttributes().getNamedItem("ID");
			elem.setIdAttributeNode(attr, true);
		}
	} catch (XPathExpressionException e) {
		e.printStackTrace();
	}
}
 
Example 5
Source File: StaxQueryXML.java    From maven-framework-project with MIT License 5 votes vote down vote up
public void query() throws ParserConfigurationException, SAXException,IOException, XPathExpressionException {
	// Standard of reading a XML file
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setNamespaceAware(true);
	DocumentBuilder builder;
	Document doc = null;
	XPathExpression expr = null;
	builder = factory.newDocumentBuilder();
	doc = builder.parse(ClassLoader.getSystemResourceAsStream("person.xml"));

	// Create a XPathFactory
	XPathFactory xFactory = XPathFactory.newInstance();

	// Create a XPath object
	XPath xpath = xFactory.newXPath();

	// Compile the XPath expression
	expr = xpath.compile("//person[firstname='Lars']/lastname/text()");
	// Run the query and get a nodeset
	Object result = expr.evaluate(doc, XPathConstants.NODESET);

	// Cast the result to a DOM NodeList
	NodeList nodes = (NodeList) result;
	for (int i = 0; i < nodes.getLength(); i++) {
		System.out.println(nodes.item(i).getNodeValue());
	}

	// New XPath expression to get the number of people with name lars
	expr = xpath.compile("count(//person[firstname='Lars'])");
	// Run the query and get the number of nodes
	Double number = (Double) expr.evaluate(doc, XPathConstants.NUMBER);
	System.out.println("Number of objects " + number);

	// Do we have more then 2 people with name lars?
	expr = xpath.compile("count(//person[firstname='Lars']) >2");
	// Run the query and get the number of nodes
	Boolean check = (Boolean) expr.evaluate(doc, XPathConstants.BOOLEAN);
	System.out.println(check);

}
 
Example 6
Source File: SAMLMessage.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
/** Get the saml attributes from the saml message which are also in the configured list */
private void buildAttributeMap() {
    // xpath initialization
    XPathFactory xFactory = XPathFactory.newInstance();
    XPath xpath = xFactory.newXPath();
    Set<Attribute> allAttributes = SAMLConfiguration.getInstance().getAvailableAttributes();
    for (Attribute attribute : allAttributes) {
        try {
            XPathExpression expression = xpath.compile(attribute.getxPath());
            Node node = (Node) expression.evaluate(xmlDocument, XPathConstants.NODE);
            if (node != null) { // the attributes that aren't available will be giving null
                // values
                String value;
                if (node instanceof Element) {
                    value = node.getTextContent();
                } else if (node instanceof Attr) {
                    value = ((Attr) node).getValue();
                } else {
                    value = node.getNodeValue();
                }
                if (value != null && !"".equals(value)) {
                    Attribute newAttrib = attribute.createCopy();
                    newAttrib.setValue(value);
                    attributeMap.put(attribute.getName(), newAttrib);
                }
            }
        } catch (XPathExpressionException e) {
            log.warn(attribute.getxPath() + " is not a valid XPath", e);
        }
    }
}
 
Example 7
Source File: DemoRequestHolder.java    From eet-client with MIT License 5 votes vote down vote up
String getXPathValue(final String xpathQuery) throws Exception {
    final XPathFactory xPathfactory = XPathFactory.newInstance();
    final XPath xpath = xPathfactory.newXPath();
    final XPathExpression expr = xpath.compile(xpathQuery);
    final Object evaluate = expr.evaluate(this.request, XPathConstants.STRING);
    return evaluate.toString();
}
 
Example 8
Source File: DOMUtil.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static
public Node selectNode(byte[] bytes, String expression) throws Exception {
	Document document = parseDocument(bytes);

	XPathExpression xPathExpression = compile(document, expression);

	return (Node)xPathExpression.evaluate(document, XPathConstants.NODE);
}
 
Example 9
Source File: AbstractXmlCartesianProduct.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private List<Node> getNodes(Document document, String path) throws XPathExpressionException
{
  XPathExpression pathExpr = xpath.compile(path);
  NodeList nodeList = (NodeList)pathExpr.evaluate(document, XPathConstants.NODESET);
  List<Node> nodes = new ArrayList<Node>();
  for (int i = 0; i < nodeList.getLength(); ++i) {
    nodes.add(nodeList.item(i));
  }
  return nodes;
}
 
Example 10
Source File: ClangAnalyzerPlistParser.java    From analysis-model with MIT License 5 votes vote down vote up
private static String extractField(final Element diag, final XPathExpression expr) throws XPathExpressionException {
    NodeList keys = (NodeList) expr.evaluate(diag, XPathConstants.NODESET);

    List<Element> elements = XmlElementUtil.nodeListToList(keys);
    if (elements.isEmpty()) {
        return "";
    }

    return elements.get(0).getTextContent();
}
 
Example 11
Source File: OvmObject.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public <E> Map<String, E> xmlToMap(String path, Document xmlDocument)
        throws Ovm3ResourceException {
    XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    try {
        XPathExpression xPathExpression = xPath.compile(path);
        NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDocument,
                XPathConstants.NODESET);
        Map<String, E> myMap = new HashMap<String, E>();
        for (int ind = 0; ind < nodeList.getLength(); ind++) {
            NodeList nodeListFor = nodeList.item(ind).getChildNodes();
            for (int index = 0; index < nodeListFor.getLength(); index++) {
                String rnode = nodeListFor.item(index).getNodeName();
                NodeList nodeListFor2 = nodeListFor.item(index).getChildNodes();
                if (nodeListFor2.getLength() > 1) {
                    /* Do we need to figure out all the sub elements here and put them in a map? */
                } else {
                    String element = nodeListFor.item(index).getNodeValue();
                    myMap.put(rnode, (E) element);
                }
            }
        }
        return myMap;
    } catch (XPathExpressionException e) {
        throw new Ovm3ResourceException("Problem parsing XML to Map:", e);
    }
}
 
Example 12
Source File: SubDocumentsParseFilter.java    From storm-crawler with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(String URL, byte[] content, DocumentFragment doc,
        ParseResult parse) {

    InputStream stream = new ByteArrayInputStream(content);

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        Document document = factory.newDocumentBuilder().parse(stream);
        Element root = document.getDocumentElement();

        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expression = xPath.compile("//url");

        NodeList nodes = (NodeList) expression.evaluate(root,
                XPathConstants.NODESET);

        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);

            expression = xPath.compile("loc");
            Node child = (Node) expression.evaluate(node,
                    XPathConstants.NODE);

            // create a subdocument for each url found in the sitemap
            ParseData parseData = parse.get(child.getTextContent());

            NodeList childs = node.getChildNodes();
            for (int j = 0; j < childs.getLength(); j++) {
                Node n = childs.item(j);
                parseData.put(n.getNodeName(), n.getTextContent());
            }
        }
    } catch (Exception e) {
        LOG.error("Error processing sitemap from {}: {}", URL, e);
    }
}
 
Example 13
Source File: XPathTest.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException, XPathFactoryConfigurationException{
		ClassLoader cl = XPathTest.class.getClassLoader();
//		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", cl);
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

//		domFactory.setNamespaceAware(true);
//		XPathFactory xpathFactory = XPathFactory.newInstance(javax.xml.xpath.XPathFactory.DEFAULT_OBJECT_MODEL_URI, "com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl", cl);
		XPathFactory xpathFactory = XPathFactory.newInstance();

		XPath xpath = xpathFactory.newXPath();
		xpath.getNamespaceContext();
		DocumentBuilder builder = domFactory.newDocumentBuilder();
		File f = new File("/mnt/dea_scratch/TRP/test/Klassikerausgaben_test/page/bsb00087391_00009.xml");
		
		Document catalog = builder.parse(f);

		final XPathExpression expr = xpath.compile("//*[contains(name(), 'Page')]/@imageWidth");

//		Object result = expr.evaluate(catalog, XPathConstants.NUMBER);
//		Double res = (Double)result;
//		System.out.println(res);
		
		Object result = expr.evaluate(catalog, XPathConstants.STRING);
		String res = (String)result;
		System.out.println(res);
		
//		Object result = expr.evaluate(catalog, XPathConstants.NODESET);
//		NodeList nodes = (NodeList) result;
//		if (nodes.getLength() > 0) {
//			String[] parents = new String[nodes.getLength()];
//			for (int i = 0; i < nodes.getLength(); i++) {
//				parents[i] = nodes.item(i).getNodeValue();
//				System.out.println(parents[i]);
//			}
//		}
	}
 
Example 14
Source File: StoredQueryManager.java    From web-feature-service with Apache License 2.0 5 votes vote down vote up
protected Element processStoredQueryElement(Element root, String handle) throws WFSException {
	try {
		NodeList nodeList = root.getElementsByTagNameNS(Constants.WFS_NAMESPACE_URI, "StoredQueryDescription");
		if (nodeList.getLength() == 0 || nodeList.getLength() > 1)
			throw new WFSException(WFSExceptionCode.OPERATION_PROCESSING_FAILED, "Failed to parse the stored query file. No stored query description provided.", handle);

		Element description = (Element)nodeList.item(0);

		// copy namespace attributes from root element
		NamedNodeMap attributes = root.getAttributes();
		for (int i = 0; i < attributes.getLength(); i++) {
			Attr attribute = (Attr)attributes.item(i);
			if (attribute.getNamespaceURI().equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
				if (attribute.getValue().equals("http://www.w3.org/2001/SMIL20/") 
						|| attribute.getValue().equals("http://www.w3.org/2001/SMIL20/Language"))
					continue;

				description.setAttributeNS(attribute.getNamespaceURI(), attribute.getName(), attribute.getValue());
			}
		}

		// remove empty text nodes
		XPathFactory xpathFactory = XPathFactory.newInstance();
		XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");  
		NodeList emptyNodeList = (NodeList)xpathExp.evaluate(root, XPathConstants.NODESET);
		for (int i = 0; i < emptyNodeList.getLength(); i++) {
			Node emptyNode = emptyNodeList.item(i);
			emptyNode.getParentNode().removeChild(emptyNode);
		}

		return description;
	} catch (XPathExpressionException e) {
		throw new WFSException(WFSExceptionCode.OPERATION_PROCESSING_FAILED, "Fatal error whilst processing the stored query.", handle, e);
	}
}
 
Example 15
Source File: SchemeGeneratorTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void serializesEnvironmentVariables() throws Exception {
  ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();

  PBXTarget rootTarget =
      new PBXNativeTarget("rootRule", AbstractPBXObjectFactory.DefaultFactory());
  rootTarget.setGlobalID("rootGID");
  rootTarget.setProductReference(
      new PBXFileReference(
          "root.a", "root.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
  rootTarget.setProductType(ProductTypes.STATIC_LIBRARY);

  Path pbxprojectPath = Paths.get("foo/Foo.xcodeproj/project.pbxproj");
  targetToProjectPathMapBuilder.put(rootTarget, pbxprojectPath);

  ImmutableMap<SchemeActionType, ImmutableMap<String, String>> environmentVariables =
      ImmutableMap.of(SchemeActionType.LAUNCH, ImmutableMap.of("ENV_VARIABLE", "IS_SET"));

  SchemeGenerator schemeGenerator =
      new SchemeGenerator(
          projectFilesystem,
          Optional.of(rootTarget),
          ImmutableSet.of(rootTarget),
          ImmutableSet.of(),
          ImmutableSet.of(),
          "TestScheme",
          Paths.get("_gen/Foo.xcworkspace/scshareddata/xcshemes"),
          true /* parallelizeBuild */,
          Optional.empty() /* wasCreatedForAppExtension */,
          Optional.empty() /* runnablePath */,
          Optional.empty() /* remoteRunnablePath */,
          SchemeActionType.DEFAULT_CONFIG_NAMES,
          targetToProjectPathMapBuilder.build(),
          Optional.of(environmentVariables),
          Optional.empty(),
          Optional.empty(),
          XCScheme.LaunchAction.LaunchStyle.AUTO,
          Optional.empty(), /* watchAdapter */
          Optional.empty() /* notificationPayloadFile */);

  Path schemePath = schemeGenerator.writeScheme();

  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document scheme = dBuilder.parse(projectFilesystem.newFileInputStream(schemePath));

  XPathFactory xpathFactory = XPathFactory.newInstance();
  XPath buildActionXpath = xpathFactory.newXPath();
  XPathExpression buildActionExpr =
      buildActionXpath.compile("//LaunchAction/EnvironmentVariables/EnvironmentVariable");
  NodeList envVariableList = (NodeList) buildActionExpr.evaluate(scheme, XPathConstants.NODESET);

  assertThat(envVariableList.getLength(), is(1));
  Node envVar = envVariableList.item(0);
  assertThat(envVar.getAttributes().getNamedItem("key").getNodeValue(), equalTo("ENV_VARIABLE"));
  assertThat(envVar.getAttributes().getNamedItem("value").getNodeValue(), equalTo("IS_SET"));
}
 
Example 16
Source File: TrpXPathProcessor.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
protected Object evaluate(Object item, XPathExpression xPathExp, QName returnType) throws XPathExpressionException {
	if(item == null || xPathExp == null) {
		throw new IllegalArgumentException("An argument is null!");
	}
	return xPathExp.evaluate(item, returnType);
}
 
Example 17
Source File: AbstractPolicySecurityTest.java    From steady with Apache License 2.0 4 votes vote down vote up
protected void verifySignatureAlgorithms(Document signedDoc, AssertionInfoMap aim) throws Exception { 
    final AssertionInfo assertInfo = aim.get(SP12Constants.ASYMMETRIC_BINDING).iterator().next();
    assertNotNull(assertInfo);
    
    final AsymmetricBinding binding = (AsymmetricBinding) assertInfo.getAssertion();
    final String expectedSignatureMethod = binding.getAlgorithmSuite().getAsymmetricSignature();
    final String expectedDigestAlgorithm = binding.getAlgorithmSuite().getDigest();
    final String expectedCanonAlgorithm  = binding.getAlgorithmSuite().getInclusiveC14n();
        
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    final NamespaceContext nsContext = this.getNamespaceContext();
    xpath.setNamespaceContext(nsContext);
    
    // Signature Algorithm
    final XPathExpression sigAlgoExpr = 
        xpath.compile("/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo" 
                          + "/ds:SignatureMethod/@Algorithm");
    
    final String sigMethod =  (String) sigAlgoExpr.evaluate(signedDoc, XPathConstants.STRING);
    assertEquals(expectedSignatureMethod, sigMethod);
    
    // Digest Method Algorithm
    final XPathExpression digestAlgoExpr = xpath.compile(
        "/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestMethod");
    
    final NodeList digestMethodNodes = 
        (NodeList) digestAlgoExpr.evaluate(signedDoc, XPathConstants.NODESET);
    
    for (int i = 0; i < digestMethodNodes.getLength(); i++) {
        Node node = (Node)digestMethodNodes.item(i);
        String digestAlgorithm = node.getAttributes().getNamedItem("Algorithm").getNodeValue();
        assertEquals(expectedDigestAlgorithm, digestAlgorithm);
    }
    
    // Canonicalization Algorithm
    final XPathExpression canonAlgoExpr =
        xpath.compile("/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo" 
                          + "/ds:CanonicalizationMethod/@Algorithm");
    final String canonMethod =  (String) canonAlgoExpr.evaluate(signedDoc, XPathConstants.STRING);
    assertEquals(expectedCanonAlgorithm, canonMethod);
}
 
Example 18
Source File: XPathExpressionWrapper.java    From XACML with MIT License 4 votes vote down vote up
@Override
public String evaluate(Object item) throws XPathExpressionException {
	XPathExpression thisXPathExpression	= this.getXpathExpressionWrapped();
	return (thisXPathExpression == null ? null : thisXPathExpression.evaluate(item));
}
 
Example 19
Source File: XPathExpressionWrapper.java    From XACML with MIT License 4 votes vote down vote up
@Override
public String evaluate(InputSource source) throws XPathExpressionException {
	XPathExpression thisXPathExpression	= this.getXpathExpressionWrapped();
	return (thisXPathExpression == null ? null : thisXPathExpression.evaluate(source));
}
 
Example 20
Source File: XMLUtils.java    From irontest with Apache License 2.0 4 votes vote down vote up
/**
 * If the input string is well formed XML, return its pretty-print format. Otherwise, return it as is.
 * If the input is null, return null.
 * @param input
 * @return
 * @throws TransformerException
 */
public static String prettyPrintXML(String input) throws TransformerException, XPathExpressionException {
    if (input == null) {
        return null;
    } else {
        Document doc;
        try {
            doc = XMLUtils.xmlStringToDOM(input);
        } catch (Exception e) {
            //  the input string is not well formed XML
            return input;
        }

        //  Remove blank text nodes from doc (if a blank text node is the only child of a parent node, leave it untouched. e.g. <c>    </c> will not become <c/>).
        //  A blank text node is a text node containing one or more whitespaces.
        //  This code block is used to mitigate a Transformer issue introduced since Java 9. Refer to http://java9.wtf/xml-transformer/.
        //      For Transformer since Java 9, text node that is sibling of element is treated like an element.
        //          e.g. <a>ccc<b>123</b></a> will be pretty printed as
        //            <a>
        //              ccc
        //              <b>123</b>
        //            </a>.
        //      If such a text node is blank, the output xml will contain an empty/blank line.
        //          e.g. <a> <b>123</b></a> will be pretty printed as
        //            <a>
        //
        //              <b>123</b>
        //            </a>
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
        NodeList blankTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < blankTextNodes.getLength(); i++) {
            Node blankTextNode = blankTextNodes.item(i);
            if (blankTextNode.getNextSibling() != null || blankTextNode.getPreviousSibling() != null) {
                blankTextNode.getParentNode().removeChild(blankTextNode);
            }
        }

        //  pretty print the xml
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        if (input.startsWith("<?xml")) {
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");  // add line break after xml declaration
        } else {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        return result.getWriter().toString();
    }
}