Java Code Examples for org.w3c.dom.Document#normalize()

The following examples show how to use org.w3c.dom.Document#normalize() . These examples are extracted from open source projects. 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
public static String[] readTitleAuthor() {
    String result[] = new String[2];
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);

    DocumentBuilder db;
    Document doc;
    try {
        File fXmlFile = new File(Constants.XMLFileName);
        db = dbf.newDocumentBuilder();
        doc = db.parse(fXmlFile);
        doc.normalize();

        result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
                .item(0).getNodeValue();

        result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
                .item(0).getNodeValue();

    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 2
private List<String> listChildren(String dn) throws ExecutionException {

        String xml = VnmcXml.LIST_CHILDREN.getXml();
        String service = VnmcXml.LIST_CHILDREN.getService();
        xml = replaceXmlValue(xml, "cookie", _cookie);
        xml = replaceXmlValue(xml, "dn", dn);

        String response = sendRequest(service, xml);

        List<String> result = new ArrayList<String>();
        Document xmlDoc = getDocument(response);
        xmlDoc.normalize();
        NodeList policyList = xmlDoc.getElementsByTagName("policyRule");
        for (int i = 0; i < policyList.getLength(); i++) {
            Node policyNode = policyList.item(i);
            result.add(policyNode.getAttributes().getNamedItem("name").getNodeValue());
        }

        return result;
    }
 
Example 3
Source Project: lams   File: UpdateWarTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
    * Writes the modified web.xml back out to war file
    * 
    * @param doc
    *            The application.xml DOM Document
    * @throws org.apache.tools.ant.DeployException
    *             in case of any problems
    */
   protected void writeWebXml(final Document doc, final OutputStream outputStream) throws DeployException {
try {
    doc.normalize();

    // Prepare the DOM document for writing
    DOMSource source = new DOMSource(doc);

    // Prepare the output file
    StreamResult result = new StreamResult(outputStream);

    // Write the DOM document to the file
    // Get Transformer
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    // Write to a file
    xformer.transform(source, result);
} catch (TransformerException tex) {
    throw new DeployException("Error writing out modified web xml ", tex);
}
   }
 
Example 4
public static String[] readTitleAuthor() {
    String result[] = new String[2];
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);

    DocumentBuilder db;
    Document doc;
    try {
        File fXmlFile = new File(Constants.XMLFileName);
        db = dbf.newDocumentBuilder();
        doc = db.parse(fXmlFile);
        doc.normalize();

        result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
                .item(0).getNodeValue();

        result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
                .item(0).getNodeValue();

    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 5
@Override
public Map<String, String> listUnAssocAsa1000v() throws ExecutionException {
    String xml = VnmcXml.LIST_UNASSOC_ASA1000V.getXml();
    String service = VnmcXml.LIST_UNASSOC_ASA1000V.getService();
    xml = replaceXmlValue(xml, "cookie", _cookie);

    String response = sendRequest(service, xml);

    Map<String, String> result = new HashMap<String, String>();
    Document xmlDoc = getDocument(response);
    xmlDoc.normalize();
    NodeList fwList = xmlDoc.getElementsByTagName("fwInstance");
    for (int j = 0; j < fwList.getLength(); j++) {
        Node fwNode = fwList.item(j);
        result.put(fwNode.getAttributes().getNamedItem("mgmtIp").getNodeValue(), fwNode.getAttributes().getNamedItem("dn").getNodeValue());
    }

    return result;
}
 
Example 6
/**
 * Common code for the it4, it6 and it10 test projects.
 * @param pDir The tests base directory.
 * @param pTargetFile Name (not path) of the transformations output file.
 * @throws Exception The test failed.
 */
public void runTestIt4( String pDir, String pTargetFile )
    throws Exception
{
    TransformMojo mojo = (TransformMojo) newMojo( pDir );
    mojo.execute();
    Document doc1 = parse( new File( pDir, "xml/doc1.xml" ) );
    doc1.normalize();
    Document doc2 = parse( new File( pDir, "target/generated-resources/xml/xslt/" + pTargetFile ) );
    doc2.normalize();
    Element doc1Element = doc1.getDocumentElement();
    assertEquals( "doc1", doc1Element.getLocalName() );
    assertNull( doc1Element.getNamespaceURI() );
    Element doc2Element = doc2.getDocumentElement();
    assertEquals( "doc2", doc2Element.getLocalName() );
    assertNull( doc2Element.getNamespaceURI() );
    Node text1 = doc1Element.getFirstChild();
    assertNotNull( text1 );
    assertNull( text1.getNextSibling() );
    assertEquals( Node.TEXT_NODE, text1.getNodeType() );
    Node text2 = doc2Element.getFirstChild();
    assertNotNull( text2 );
    assertNull( text2.getNextSibling() );
    assertEquals( Node.TEXT_NODE, text2.getNodeType() );
    assertEquals( text1.getNodeValue(), text2.getNodeValue() );
}
 
Example 7
/**
 * Builds the it5 test project.
 * @throws Exception The test failed.
 */
public void testIt5()
    throws Exception
{
    final String dir = "src/test/it5";
    runTest( dir );
    Document doc1 = parse( new File( dir, "xml/doc1.xml" ) );
    doc1.normalize();
    Document doc2 = parse( new File( dir, "target/generated-resources/xml/xslt/doc1.xml" ) );
    doc2.normalize();
    Element doc1Element = doc1.getDocumentElement();
    assertEquals( "doc1", doc1Element.getLocalName() );
    assertNull( doc1Element.getNamespaceURI() );
    Element doc2Element = doc2.getDocumentElement();
    assertEquals( "doc2", doc2Element.getLocalName() );
    assertNull( doc2Element.getNamespaceURI() );
    Node text1 = doc1Element.getFirstChild();
    assertNotNull( text1 );
    assertNull( text1.getNextSibling() );
    assertEquals( Node.TEXT_NODE, text1.getNodeType() );
    Node text2 = doc2Element.getFirstChild();
    assertNotNull( text2 );
    assertNull( text2.getNextSibling() );
    assertEquals( Node.TEXT_NODE, text2.getNodeType() );
    assertEquals( text2.getNodeValue(), "parameter passed in" );
}
 
Example 8
private List<String> listNatPolicies(String tenantName) throws ExecutionException {

        String xml = VnmcXml.LIST_NAT_POLICIES.getXml();
        String service = VnmcXml.LIST_NAT_POLICIES.getService();
        xml = replaceXmlValue(xml, "cookie", _cookie);
        xml = replaceXmlValue(xml, "vdcdn", getDnForTenantVDC(tenantName));

        String response = sendRequest(service, xml);

        List<String> result = new ArrayList<String>();
        Document xmlDoc = getDocument(response);
        xmlDoc.normalize();
        NodeList policyList = xmlDoc.getElementsByTagName("pair");
        for (int i = 0; i < policyList.getLength(); i++) {
            Node policyNode = policyList.item(i);
            result.add(policyNode.getAttributes().getNamedItem("key").getNodeValue());
        }

        return result;
    }
 
Example 9
Source Project: openbd-core   File: XmlNew.java    License: GNU General Public License v3.0 6 votes vote down vote up
public cfData execute(cfSession _session, List<cfData> parameters) throws cfmRunTimeException {
	boolean caseSensitive = false;
	if (parameters.size() == 1)
		caseSensitive = cfBooleanData.getcfBooleanData(parameters.get(0).getString()).getBoolean();
	try {
		DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
		fact.setNamespaceAware(true);
		DocumentBuilder parser = fact.newDocumentBuilder();

		Document doc = parser.newDocument();
		doc.normalize();
		return new cfXmlData(doc, caseSensitive);
	} catch (ParserConfigurationException ex) {
		throw new cfmRunTimeException(catchDataFactory.javaMethodException("errorCode.javaException", ex.getClass().getName(), ex.getMessage(), ex));
	}
}
 
Example 10
public static String[] readTitleAuthor() {
    String result[] = new String[2];
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);

    DocumentBuilder db;
    Document doc;
    try {
        File fXmlFile = new File(Constants.XMLFileName);
        db = dbf.newDocumentBuilder();
        doc = db.parse(fXmlFile);
        doc.normalize();

        result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
                .item(0).getNodeValue();

        result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
                .item(0).getNodeValue();

    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 11
public static String[] readTitleAuthor() {
    String result[] = new String[2];
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);

    DocumentBuilder db;
    Document doc;
    try {
        File fXmlFile = new File(Constants.XMLFileName);
        db = dbf.newDocumentBuilder();
        doc = db.parse(fXmlFile);
        doc.normalize();

        result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
                .item(0).getNodeValue();

        result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
                .item(0).getNodeValue();

    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 12
public static String[] readTitleAuthor() {
    String result[] = new String[2];
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);

    DocumentBuilder db;
    Document doc;
    try {
        File fXmlFile = new File(Constants.XMLFileName);
        db = dbf.newDocumentBuilder();
        doc = db.parse(fXmlFile);
        doc.normalize();

        result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
                .item(0).getNodeValue();

        result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
                .item(0).getNodeValue();

    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 13
Source Project: milkman   File: XmlContentType.java    License: MIT License 5 votes vote down vote up
public static String toPrettyString(String xml, int indent) {
    try {
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        document.normalize();
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']",
                                                      document,
                                                      XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        log.warn("Failed to format xml", e);
    }
    return xml;
}
 
Example 14
Source Project: tsml   File: BIFReader.java    License: GNU General Public License v3.0 5 votes vote down vote up
public BIFReader processString(String sStr) throws Exception {
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       factory.setValidating(true);
	Document doc = factory.newDocumentBuilder().parse(new org.xml.sax.InputSource(new StringReader(sStr)));
       doc.normalize();
       buildInstances(doc, "from-string");
       buildStructure(doc);
       return this;
}
 
Example 15
Source Project: aws-sdk-java-v2   File: PomTransformer.java    License: Apache License 2.0 5 votes vote down vote up
public final void transform(Path file) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(file.toFile());

    doc.normalize();
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']",
                                                  doc,
                                                  XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }

    updateDocument(doc);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", 4);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(file.toFile());
    transformer.transform(source, result);
}
 
Example 16
Source Project: ECTester   File: EC_Store.java    License: MIT License 5 votes vote down vote up
private void parse() throws SAXException, ParserConfigurationException, IOException {

        InputStream categories = this.getClass().getResourceAsStream("/cz/crcs/ectester/data/categories.xml");
        if (categories == null) {
            throw new IOException();
        }
        Document categoriesDoc = db.parse(categories);
        categories.close();
        categoriesDoc.normalize();

        NodeList catList = categoriesDoc.getElementsByTagName("category");

        this.categories = new TreeMap<>();
        for (int i = 0; i < catList.getLength(); ++i) {
            Node catNode = catList.item(i);
            if (catNode instanceof Element) {
                Element catElem = (Element) catNode;
                Node name = catElem.getElementsByTagName("name").item(0);
                Node dir = catElem.getElementsByTagName("directory").item(0);
                Node desc = catElem.getElementsByTagName("desc").item(0);

                EC_Category category = parseCategory(name.getTextContent(), dir.getTextContent(), desc.getTextContent());
                this.categories.put(name.getTextContent(), category);
            } else {
                throw new SAXException("?");
            }
        }
    }
 
Example 17
Source Project: SAMLRaider   File: XMLHelpers.java    License: MIT License 5 votes vote down vote up
/**
 * Removes all signatures in a given XML document
 *
 * @param document
 *            document in which the signature should be removed
 * @return number of removed signatures
 */
public int removeAllSignatures(Document document) {
	NodeList nl = getSignatures(document);
	int nrSig = nl.getLength();

	for (int i = 0; i < nrSig; i++) {
		Node parent = nl.item(0).getParentNode();
		parent.removeChild(nl.item(0));
	}
	removeEmptyTags(document);
	document.normalize();
	return nrSig;
}
 
Example 18
Source Project: aspectj-maven-plugin   File: EclipseAjcMojo.java    License: MIT License 5 votes vote down vote up
/**
 * write document to the file
 *
 * @param document
 * @param file
 * @throws TransformerException
 * @throws FileNotFoundException
 */
private void writeDocument( Document document, File file )
    throws TransformerException, FileNotFoundException
{
    document.normalize();
    DOMSource source = new DOMSource( document );
    StreamResult result = new StreamResult( new FileOutputStream( file ) );
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
    transformer.transform( source, result );
}
 
Example 19
Source Project: xmlunit   File: Diff.java    License: Apache License 2.0 5 votes vote down vote up
private Document getNormalizedDocument(Document orig) {
    if (!XMLUnit.getNormalize()) {
        return orig;
    }
    Document d = (Document) orig.cloneNode(true);
    d.normalize();
    return d;
}
 
Example 20
public void createExplicitTagFile(String fileName) throws SAXException, IOException, TransformerException {
		Document doc = parseXmlFile(fileName);
		doc.normalize(); // https://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
		
		// TODO: modify 
		
		transformNodesListToExplicitTags(doc.getElementsByTagName(TEXT_LINE_ELEMENT_NAME));
		transformNodesListToExplicitTags(doc.getElementsByTagName(WORD_ELEMENT_NAME));

		
//		System.out.println(createDocumentString(doc));
	}