com.helger.xml.XMLFactory Java Examples
The following examples show how to use
com.helger.xml.XMLFactory.
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: DOMReaderDefaultSettings.java From ph-commons with Apache License 2.0 | 6 votes |
public static boolean requiresNewXMLParser () { return s_aRWLock.readLockedBoolean ( () -> { // Force a new XML parser? if (s_bDefaultRequiresNewXMLParserExplicitly) return true; if (s_bDefaultNamespaceAware != XMLFactory.DEFAULT_DOM_NAMESPACE_AWARE || s_bDefaultValidating != XMLFactory.DEFAULT_DOM_VALIDATING || s_bDefaultIgnoringElementContentWhitespace != XMLFactory.DEFAULT_DOM_IGNORING_ELEMENT_CONTENT_WHITESPACE || s_bDefaultExpandEntityReferences != XMLFactory.DEFAULT_DOM_EXPAND_ENTITY_REFERENCES || s_bDefaultIgnoringComments != XMLFactory.DEFAULT_DOM_IGNORING_COMMENTS || s_bDefaultCoalescing != XMLFactory.DEFAULT_DOM_COALESCING || s_aDefaultSchema != null || s_bDefaultXIncludeAware != XMLFactory.DEFAULT_DOM_XINCLUDE_AWARE || s_aDefaultProperties.isNotEmpty () || s_aDefaultFeatures.isNotEmpty ()) return true; // Special case for JDK > 1.7.0_45 because of maximum entity expansion // See http://docs.oracle.com/javase/tutorial/jaxp/limits/limits.html return s_aDefaultEntityResolver != null; }); }
Example #2
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 6 votes |
@Test public void testOrderNamespaces () { XMLWriterSettings aSettings = new XMLWriterSettings ().setIndent (EXMLSerializeIndent.NONE) .setUseDoubleQuotesForAttributes (false); // default order final Document aDoc = XMLFactory.newDocument (); final Element e = (Element) aDoc.appendChild (aDoc.createElement ("a")); e.setAttributeNS ("urn:ns3", "c", "1"); e.setAttributeNS ("urn:ns2", "b", "2"); e.setAttributeNS ("urn:ns1", "a", "3"); assertEquals ("<a xmlns='urn:ns1' a='3' xmlns:ns0='urn:ns2' ns0:b='2' xmlns:ns1='urn:ns3' ns1:c='1' />", XMLWriter.getNodeAsString (e, aSettings)); aSettings = aSettings.setOrderAttributesAndNamespaces (true); assertEquals ("<a xmlns='urn:ns1' xmlns:ns0='urn:ns2' xmlns:ns1='urn:ns3' a='3' ns0:b='2' ns1:c='1' />", XMLWriter.getNodeAsString (e, aSettings)); }
Example #3
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 6 votes |
@Test public void testOrderAttributes () { XMLWriterSettings aSettings = new XMLWriterSettings ().setIndent (EXMLSerializeIndent.NONE) .setUseDoubleQuotesForAttributes (false); // default order final Document aDoc = XMLFactory.newDocument (); final Element e = (Element) aDoc.appendChild (aDoc.createElement ("a")); e.setAttribute ("c", "1"); e.setAttribute ("b", "2"); e.setAttribute ("a", "3"); // Attributes are ordered automatically in DOM! assertEquals ("<a a='3' b='2' c='1' />", XMLWriter.getNodeAsString (e, aSettings)); aSettings = aSettings.setOrderAttributesAndNamespaces (true); assertEquals ("<a a='3' b='2' c='1' />", XMLWriter.getNodeAsString (e, aSettings)); }
Example #4
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 6 votes |
@Test public void testNumericReferencesXML11 () throws TransformerException { for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i) if (!XMLCharHelper.isInvalidXMLTextChar (EXMLSerializeVersion.XML_11, (char) i)) { final String sText = "abc" + (char) i + "def"; final Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_11); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root")); eRoot.appendChild (aDoc.createTextNode (sText)); final Transformer aTransformer = XMLTransformerFactory.newTransformer (); aTransformer.setOutputProperty (OutputKeys.ENCODING, StandardCharsets.UTF_8.name ()); aTransformer.setOutputProperty (OutputKeys.INDENT, "no"); aTransformer.setOutputProperty (OutputKeys.VERSION, EXMLVersion.XML_11.getVersion ()); final StringStreamResult aRes = new StringStreamResult (); aTransformer.transform (new DOMSource (aDoc), aRes); final String sXML = aRes.getAsString (); final Document aDoc2 = DOMReader.readXMLDOM (sXML); assertNotNull (aDoc2); } }
Example #5
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 6 votes |
@Test public void testNumericReferencesXML10 () throws TransformerException { for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i) if (!XMLCharHelper.isInvalidXMLTextChar (EXMLSerializeVersion.XML_10, (char) i)) { final String sText = "abc" + (char) i + "def"; final Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_10); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root")); eRoot.appendChild (aDoc.createTextNode (sText)); // Use regular transformer final Transformer aTransformer = XMLTransformerFactory.newTransformer (); aTransformer.setOutputProperty (OutputKeys.ENCODING, StandardCharsets.UTF_8.name ()); aTransformer.setOutputProperty (OutputKeys.INDENT, "yes"); aTransformer.setOutputProperty (OutputKeys.VERSION, EXMLVersion.XML_10.getVersion ()); final StringStreamResult aRes = new StringStreamResult (); aTransformer.transform (new DOMSource (aDoc), aRes); final String sXML = aRes.getAsString (); final Document aDoc2 = DOMReader.readXMLDOM (sXML); assertNotNull (aDoc2); } }
Example #6
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 6 votes |
@Test public void testWriteCDATAAsText () { final Document doc = XMLFactory.newDocument (); final XMLWriterSettings aXWS = new XMLWriterSettings ().setWriteCDATAAsText (true); // Containing the forbidden CDATA end marker Element e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a]]>b")); assertEquals ("<a>a]]>b</a>" + CRLF, XMLWriter.getNodeAsString (e, aXWS)); // Containing more than one forbidden CDATA end marker e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a]]>b]]>c")); assertEquals ("<a>a]]>b]]>c</a>" + CRLF, XMLWriter.getNodeAsString (e, aXWS)); // Containing a complete CDATA section e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a<![CDATA[x]]>b")); assertEquals ("<a>a<![CDATA[x]]>b</a>" + CRLF, XMLWriter.getNodeAsString (e, aXWS)); }
Example #7
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 6 votes |
@Test public void testNestedCDATAs () { final Document doc = XMLFactory.newDocument (); // Containing the forbidden CDATA end marker Element e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a]]>b")); assertEquals ("<a><![CDATA[a]]]]><![CDATA[>b]]></a>" + CRLF, XMLWriter.getNodeAsString (e)); // Containing more than one forbidden CDATA end marker e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a]]>b]]>c")); assertEquals ("<a><![CDATA[a]]]]><![CDATA[>b]]]]><![CDATA[>c]]></a>" + CRLF, XMLWriter.getNodeAsString (e)); // Containing a complete CDATA section e = doc.createElement ("a"); e.appendChild (doc.createCDATASection ("a<![CDATA[x]]>b")); assertEquals ("<a><![CDATA[a<![CDATA[x]]]]><![CDATA[>b]]></a>" + CRLF, XMLWriter.getNodeAsString (e)); }
Example #8
Source File: DOMReaderSettings.java From ph-commons with Apache License 2.0 | 6 votes |
public boolean requiresNewXMLParser () { // Force a new XML parser? if (m_bRequiresNewXMLParserExplicitly) return true; if (m_bNamespaceAware != XMLFactory.DEFAULT_DOM_NAMESPACE_AWARE || m_bValidating != XMLFactory.DEFAULT_DOM_VALIDATING || m_bIgnoringElementContentWhitespace != XMLFactory.DEFAULT_DOM_IGNORING_ELEMENT_CONTENT_WHITESPACE || m_bExpandEntityReferences != XMLFactory.DEFAULT_DOM_EXPAND_ENTITY_REFERENCES || m_bIgnoringComments != XMLFactory.DEFAULT_DOM_IGNORING_COMMENTS || m_bCoalescing != XMLFactory.DEFAULT_DOM_COALESCING || m_aSchema != null || m_bXIncludeAware != XMLFactory.DEFAULT_DOM_XINCLUDE_AWARE || m_aProperties.isNotEmpty () || m_aFeatures.isNotEmpty ()) return true; // Special case for JDK > 1.7.0_45 because of maximum entity expansion // See http://docs.oracle.com/javase/tutorial/jaxp/limits/limits.html return m_aEntityResolver != null; }
Example #9
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 5 votes |
@Test public void testWithoutEmitNamespaces () { final Document aDoc = XMLFactory.newDocument (); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS ("ns1url", "root")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child1")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child2")); final XMLWriterSettings aSettings = new XMLWriterSettings ().setCharset (StandardCharsets.ISO_8859_1) .setIndent (EXMLSerializeIndent.NONE); String s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + "<root xmlns=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" />" + "</root>", s); aSettings.setEmitNamespaces (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + "<root>" + "<child1 />" + "<child2 />" + "</root>", s); aSettings.setPutNamespaceContextPrefixesInRoot (true); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + "<root>" + "<child1 />" + "<child2 />" + "</root>", s); }
Example #10
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 5 votes |
@Test public void testXMLVersionNumber () { Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_10); aDoc.appendChild (aDoc.createElement ("any")); String sXML = XMLWriter.getNodeAsString (aDoc); assertEquals ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + CRLF + "<any />" + CRLF, sXML); aDoc = XMLFactory.newDocument (EXMLVersion.XML_11); aDoc.appendChild (aDoc.createElement ("any")); sXML = XMLWriter.getNodeAsString (aDoc); assertEquals ("<?xml version=\"1.1\" encoding=\"UTF-8\" standalone=\"no\"?>" + CRLF + "<any />" + CRLF, sXML); }
Example #11
Source File: MicroHelperTest.java From ph-commons with Apache License 2.0 | 5 votes |
@Test public void testConvertToMicroNode () throws SAXException, IOException, ParserConfigurationException { final String sXML = "<?xml version='1.0'?>" + "<!DOCTYPE root [ <!ENTITY sc \"sc.exe\"> <!ELEMENT root (child, child2)> <!ELEMENT child (#PCDATA)> <!ELEMENT child2 (#PCDATA)> ]>" + "<root attr='value'>" + "<![CDATA[hihi]]>" + "text" + "≻" + "<child xmlns='http://myns' a='b' />" + "<child2 />" + "<!-- comment -->" + "<?stylesheet x y z?>" + "</root>"; final DocumentBuilderFactory aDBF = XMLFactory.createDefaultDocumentBuilderFactory (); aDBF.setCoalescing (false); aDBF.setIgnoringComments (false); final Document doc = aDBF.newDocumentBuilder ().parse (new StringInputStream (sXML, StandardCharsets.ISO_8859_1)); assertNotNull (doc); final IMicroNode aNode = MicroHelper.convertToMicroNode (doc); assertNotNull (aNode); try { MicroHelper.convertToMicroNode (null); fail (); } catch (final NullPointerException ex) {} }
Example #12
Source File: CollectingTransformErrorListenerTest.java From ph-commons with Apache License 2.0 | 5 votes |
@Test public void testAll () throws TransformerConfigurationException, TransformerException { final CollectingTransformErrorListener el = new CollectingTransformErrorListener (); final TransformerFactory fac = XMLTransformerFactory.createTransformerFactory (el.andThen (new LoggingTransformErrorListener (L_EN)), new LoggingTransformURIResolver ()); assertNotNull (fac); // Read valid XSLT Templates t1 = XMLTransformerFactory.newTemplates (fac, new ClassPathResource ("xml/test1.xslt")); assertNotNull (t1); // May contain warning in JDK 1.7 // (http://javax.xml.XMLConstants/property/accessExternalDTD is unknown) assertTrue (el.getErrorList ().containsNoError ()); // Try a real transformation { final Document aDoc = XMLFactory.newDocument (); t1.newTransformer () .transform (TransformSourceFactory.create (new ClassPathResource ("xml/xslt1.xml")), new DOMResult (aDoc)); assertNotNull (aDoc); assertNotNull (aDoc.getDocumentElement ()); assertEquals ("html", aDoc.getDocumentElement ().getTagName ()); } // Read valid XSLT (with import) t1 = XMLTransformerFactory.newTemplates (fac, new ClassPathResource ("xml/test2.xslt")); assertNotNull (t1); // May contain warning in JDK 1.7 // (http://javax.xml.XMLConstants/property/accessExternalDTD is unknown) assertTrue (el.getErrorList ().containsNoError ()); // Read invalid XSLT assertNull (XMLTransformerFactory.newTemplates (fac, new ClassPathResource ("test1.txt"))); assertTrue (el.getErrorList ().containsAtLeastOneError ()); CommonsTestHelper.testToStringImplementation (el); }
Example #13
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 5 votes |
@Test public void testAttributesWithNamespaces () { final XMLWriterSettings aSettings = new XMLWriterSettings ().setIndent (EXMLSerializeIndent.NONE) .setCharset (StandardCharsets.ISO_8859_1); final Document aDoc = XMLFactory.newDocument (); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS ("ns1url", "root")); final Element e1 = (Element) eRoot.appendChild (aDoc.createElementNS ("ns2url", "child1")); e1.setAttributeNS ("ns2url", "attr1", "value1"); final Element e2 = (Element) eRoot.appendChild (aDoc.createElementNS ("ns2url", "child2")); e2.setAttributeNS ("ns3url", "attr2", "value2"); String s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + "<root xmlns=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" ns0:attr1=\"value1\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" xmlns:ns1=\"ns3url\" ns1:attr2=\"value2\" />" + "</root>", s); assertEquals (s, XMLWriter.getNodeAsString (DOMReader.readXMLDOM (s), aSettings)); aSettings.setEmitNamespaces (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + "<root>" + "<child1 attr1=\"value1\" />" + "<child2 attr2=\"value2\" />" + "</root>", s); }
Example #14
Source File: DOMReaderSettingsTest.java From ph-commons with Apache License 2.0 | 5 votes |
@Test public void testDefault () { final DOMReaderSettings aDRS = new DOMReaderSettings (); assertNotNull (aDRS); assertFalse (aDRS.requiresNewXMLParser ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_NAMESPACE_AWARE, aDRS.isNamespaceAware ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_VALIDATING, aDRS.isValidating ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_IGNORING_ELEMENT_CONTENT_WHITESPACE, aDRS.isIgnoringElementContentWhitespace ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_EXPAND_ENTITY_REFERENCES, aDRS.isExpandEntityReferences ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_IGNORING_COMMENTS, aDRS.isIgnoringComments ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_COALESCING, aDRS.isCoalescing ()); assertNull (aDRS.getSchema ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_XINCLUDE_AWARE, aDRS.isXIncludeAware ()); assertNull (aDRS.getEntityResolver ()); assertNotNull (aDRS.getErrorHandler ()); assertNotNull (aDRS.exceptionCallbacks ()); assertFalse (aDRS.isRequiresNewXMLParserExplicitly ()); assertFalse (aDRS.requiresNewXMLParser ()); aDRS.setRequiresNewXMLParserExplicitly (true); assertTrue (aDRS.isRequiresNewXMLParserExplicitly ()); assertTrue (aDRS.requiresNewXMLParser ()); aDRS.setRequiresNewXMLParserExplicitly (false); assertFalse (aDRS.isRequiresNewXMLParserExplicitly ()); assertFalse (aDRS.requiresNewXMLParser ()); }
Example #15
Source File: DOMReaderDefaultSettingsTest.java From ph-commons with Apache License 2.0 | 5 votes |
@Test public void testDefault () { assertFalse (DOMReaderDefaultSettings.requiresNewXMLParser ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_NAMESPACE_AWARE, DOMReaderDefaultSettings.isNamespaceAware ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_VALIDATING, DOMReaderDefaultSettings.isValidating ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_IGNORING_ELEMENT_CONTENT_WHITESPACE, DOMReaderDefaultSettings.isIgnoringElementContentWhitespace ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_EXPAND_ENTITY_REFERENCES, DOMReaderDefaultSettings.isExpandEntityReferences ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_IGNORING_COMMENTS, DOMReaderDefaultSettings.isIgnoringComments ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_COALESCING, DOMReaderDefaultSettings.isCoalescing ()); assertNull (DOMReaderDefaultSettings.getSchema ()); CommonsAssert.assertEquals (XMLFactory.DEFAULT_DOM_XINCLUDE_AWARE, DOMReaderDefaultSettings.isXIncludeAware ()); assertNull (DOMReaderDefaultSettings.getEntityResolver ()); assertNotNull (DOMReaderDefaultSettings.getErrorHandler ()); assertNotNull (DOMReaderDefaultSettings.exceptionCallbacks ()); assertFalse (DOMReaderDefaultSettings.isRequiresNewXMLParserExplicitly ()); assertFalse (DOMReaderDefaultSettings.requiresNewXMLParser ()); DOMReaderDefaultSettings.setRequiresNewXMLParserExplicitly (true); assertTrue (DOMReaderDefaultSettings.isRequiresNewXMLParserExplicitly ()); assertTrue (DOMReaderDefaultSettings.requiresNewXMLParser ()); DOMReaderDefaultSettings.setRequiresNewXMLParserExplicitly (false); assertFalse (DOMReaderDefaultSettings.isRequiresNewXMLParserExplicitly ()); assertFalse (DOMReaderDefaultSettings.requiresNewXMLParser ()); }
Example #16
Source File: IJAXBWriter.java From ph-commons with Apache License 2.0 | 5 votes |
/** * Convert the passed object to a new DOM document (write). * * @param aObject * The object to be converted. May not be <code>null</code>. * @return <code>null</code> if converting the document failed. */ @Nullable default Document getAsDocument (@Nonnull final JAXBTYPE aObject) { // No need for charset fix, because the document is returned in an internal // representation with String content final Document aDoc = XMLFactory.newDocument (); return write (aObject, TransformResultFactory.create (aDoc)).isSuccess () ? aDoc : null; }
Example #17
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 4 votes |
@Test public void testXHTMLBracketMode () { final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING; final Document aDoc = XMLFactory.newDocument ("html", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI); final Element aHead = (Element) aDoc.getDocumentElement () .appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "head")); aHead.appendChild (aDoc.createTextNode ("Hallo")); final Element aBody = (Element) aDoc.getDocumentElement () .appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "body")); aBody.appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "img")); // test including doc type final String sResult = XMLWriter.getNodeAsString (aDoc, XMLWriterSettings.createForXHTML ()); assertEquals ("<!DOCTYPE html PUBLIC \"" + DOCTYPE_XHTML10_QNAME + "\" \"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<body>" + CRLF + sINDENT + sINDENT + // self closed tag "<img />" + CRLF + sINDENT + "</body>" + CRLF + "</html>" + CRLF, sResult); }
Example #18
Source File: CreateInvoiceFromScratchFuncTest.java From ph-ubl with Apache License 2.0 | 4 votes |
/** * This is an example that creates an XML schema compliant invoice <b>AND</b> * adds an extension as requested in issue #10 */ @Test public void testCreateInvoiceFromScratchWithExtension () { final String sCurrency = "EUR"; // Create domain object final InvoiceType aInvoice = new InvoiceType (); // Fill it aInvoice.setID ("Dummy Invoice number"); aInvoice.setIssueDate (PDTXMLConverter.getXMLCalendarDateNow ()); final SupplierPartyType aSupplier = new SupplierPartyType (); aInvoice.setAccountingSupplierParty (aSupplier); final CustomerPartyType aCustomer = new CustomerPartyType (); aInvoice.setAccountingCustomerParty (aCustomer); final MonetaryTotalType aMT = new MonetaryTotalType (); aMT.setPayableAmount (BigDecimal.TEN).setCurrencyID (sCurrency); aInvoice.setLegalMonetaryTotal (aMT); final InvoiceLineType aLine = new InvoiceLineType (); aLine.setID ("1"); final ItemType aItem = new ItemType (); aLine.setItem (aItem); aLine.setLineExtensionAmount (BigDecimal.TEN).setCurrencyID (sCurrency); aInvoice.addInvoiceLine (aLine); // Example extension content from issue #10: /** * <pre> <aife:FactureExtension xmlns:aife="urn:AIFE:Facture:Extension"> <aife:CategoryCode>XX</aife:CategoryCode> </aife:FactureExtension> * </pre> */ final Document aDoc = XMLFactory.newDocument (); final String sNamespaceURI = "urn:AIFE:Facture:Extension"; final Node eRoot = aDoc.appendChild (aDoc.createElementNS (sNamespaceURI, "FactureExtension")); final Node eCategoryCode = eRoot.appendChild (aDoc.createElementNS (sNamespaceURI, "CategoryCode")); eCategoryCode.appendChild (aDoc.createTextNode ("XX")); // Now add the extension final UBLExtensionsType aExtensions = new UBLExtensionsType (); final UBLExtensionType aExtension = new UBLExtensionType (); final ExtensionContentType aExtensionContent = new ExtensionContentType (); // Add the root element - NEVER use the whole document! aExtensionContent.setAny (aDoc.getDocumentElement ()); aExtension.setExtensionContent (aExtensionContent); aExtensions.addUBLExtension (aExtension); aInvoice.setUBLExtensions (aExtensions); // Write to disk ("as is") ESuccess eSuccess = UBL21Writer.invoice ().write (aInvoice, new File ("target/dummy-invoice-with-extension.xml")); assertTrue (eSuccess.isSuccess ()); // doesn't work as expected yet if (false) { // Write to disk with a custom namespace prefix mapping final UBL21WriterBuilder <InvoiceType> aBuilder = UBL21Writer.invoice (); final MapBasedNamespaceContext aCtx = (MapBasedNamespaceContext) aBuilder.getNamespaceContext (); aCtx.addMapping ("aife", sNamespaceURI); eSuccess = aBuilder.write (aInvoice, new File ("target/dummy-invoice-with-extension-and-ns.xml")); assertTrue (eSuccess.isSuccess ()); } }
Example #19
Source File: AbstractSchematronXSLTBasedResource.java From ph-schematron with Apache License 2.0 | 4 votes |
@Nullable public final Document applySchematronValidation (@Nonnull final Node aXMLNode, @Nullable final String sBaseURI) throws TransformerException { ValueEnforcer.notNull (aXMLNode, "XMLNode"); final ISchematronXSLTBasedProvider aXSLTProvider = getXSLTProvider (); if (aXSLTProvider == null || !aXSLTProvider.isValidSchematron ()) { // We cannot progress because of invalid Schematron return null; } // Debug print the created XSLT document if (SchematronDebug.isShowCreatedXSLT ()) LOGGER.info ("Created XSLT document: " + XMLWriter.getNodeAsString (aXSLTProvider.getXSLTDocument ())); // Create result document final Document ret = XMLFactory.newDocument (); // Create the transformer object from the templates specified in the // constructor final Transformer aTransformer = aXSLTProvider.getXSLTTransformer (); // Apply customizations // Ensure an error listener is present if (m_aCustomErrorListener != null) aTransformer.setErrorListener (m_aCustomErrorListener); else aTransformer.setErrorListener (new LoggingTransformErrorListener (Locale.US)); // Set the optional URI Resolver if (m_aCustomURIResolver != null) aTransformer.setURIResolver (m_aCustomURIResolver); // Set all custom parameters if (m_aCustomParameters != null) for (final Map.Entry <String, ?> aEntry : m_aCustomParameters.entrySet ()) aTransformer.setParameter (aEntry.getKey (), aEntry.getValue ()); if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Applying Schematron XSLT on XML [start]"); // Enable this for hardcore Saxon debugging only if (false) if (aTransformer.getClass ().getName ().equals ("net.sf.saxon.jaxp.TransformerImpl")) { final XsltTransformer aXT = ((TransformerImpl) aTransformer).getUnderlyingXsltTransformer (); aXT.setMessageListener ( (a, b, c, d) -> LOGGER.info ("MessageListener2: " + a + ", " + b + ", " + c + ", " + d)); aXT.setTraceFunctionDestination (new StandardLogger (System.err)); if (false) aXT.getUnderlyingController ().setTraceListener (new XSLTTraceListener ()); if (false) { final XSLTTraceListener aTL = new XSLTTraceListener (); aTL.setOutputDestination (new StandardLogger (System.err)); aXT.getUnderlyingController ().setTraceListener (TraceEventMulticaster.add (aTL, null)); } if (false) System.out.println ("mode=" + aXT.getInitialMode ()); if (false) System.out.println ("temp=" + aXT.getInitialTemplate ()); if (false) System.out.println (aTransformer.getOutputProperties ()); } // Do the main transformation { final DOMSource aSource = new DOMSource (aXMLNode); aSource.setSystemId (sBaseURI); aTransformer.transform (aSource, new DOMResult (ret)); } if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Applying Schematron XSLT on XML [end]"); // Debug print the created SVRL document if (SchematronDebug.isShowCreatedSVRL ()) LOGGER.info ("Created SVRL:\n" + XMLWriter.getNodeAsString (ret)); return ret; }
Example #20
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 4 votes |
@Test public void testXMLDeclaration () { final Document aDoc = XMLFactory.newDocument (); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root")); eRoot.appendChild (aDoc.createElement ("child1")); final XMLWriterSettings aSettings = new XMLWriterSettings (); String s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + CRLF + "<root>" + CRLF + " <child1 />" + CRLF + "</root>" + CRLF, s); aSettings.setNewLineAfterXMLDeclaration (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + "<root>" + CRLF + " <child1 />" + CRLF + "</root>" + CRLF, s); aSettings.setNewLineAfterXMLDeclaration (true); aSettings.setSerializeXMLDeclaration (EXMLSerializeXMLDeclaration.EMIT_NO_STANDALONE); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + CRLF + "<root>" + CRLF + " <child1 />" + CRLF + "</root>" + CRLF, s); }
Example #21
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 4 votes |
@Test public void testXHTMLIndent () { final XMLWriterSettings xs = XMLWriterSettings.createForXHTML ().setSerializeDocType (EXMLSerializeDocType.IGNORE); final String sINDENT = xs.getIndentationString (); final Document aDoc = XMLFactory.newDocument ("html", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI); final Element aHead = (Element) aDoc.getDocumentElement () .appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "head")); aHead.appendChild (aDoc.createTextNode ("Hallo")); final Element aBody = (Element) aDoc.getDocumentElement () .appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "body")); final Element aPre = (Element) aBody.appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "pre")); final Element aDiv = (Element) aPre.appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "div")); aDiv.appendChild (aDoc.createTextNode ("pre formatted")); assertEquals ("<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<body>" + CRLF + sINDENT + sINDENT + // pre not indented "<pre><div>pre formatted</div></pre>" + CRLF + sINDENT + "</body>" + CRLF + "</html>" + CRLF, XMLWriter.getNodeAsString (aDoc, xs)); // Special handling with void element aPre.removeChild (aDiv); aPre.appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "img")); assertEquals ("<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<body>" + CRLF + sINDENT + sINDENT + // pre not indented "<pre><img /></pre>" + CRLF + sINDENT + "</body>" + CRLF + "</html>" + CRLF, XMLWriter.getNodeAsString (aDoc, xs)); }
Example #22
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 4 votes |
@Test public void testWriteXMLMultiThreaded () { final String sSPACER = " "; final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING; final String sTAGNAME = "notext"; CommonsTestHelper.testInParallel (1000, () -> { // Java 1.6 JAXP handles things differently final String sSerTagName = "<" + sTAGNAME + "></" + sTAGNAME + ">"; final Document doc = XMLFactory.newDocument ("html", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI); final Element aHead = (Element) doc.getDocumentElement () .appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, "head")); aHead.appendChild (doc.createTextNode ("Hallo")); final Element aNoText = (Element) doc.getDocumentElement () .appendChild (doc.createElementNS (DOCTYPE_XHTML10_URI, sTAGNAME)); aNoText.appendChild (doc.createTextNode ("")); // test including doc type final String sResult = XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ()); assertEquals ("<!DOCTYPE html PUBLIC \"" + DOCTYPE_XHTML10_QNAME + "\"" + sSPACER + "\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + sSerTagName + CRLF + "</html>" + CRLF, sResult); assertEquals (sResult, XMLWriter.getNodeAsString (doc, XMLWriterSettings.createForXHTML ())); }); }
Example #23
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 4 votes |
@Test public void testHTML4BracketMode () { final String sINDENT = XMLWriterSettings.DEFAULT_INDENTATION_STRING; final Document aDoc = XMLFactory.newDocument ("html", DOCTYPE_XHTML10_QNAME, DOCTYPE_XHTML10_URI); final Element aHead = (Element) aDoc.getDocumentElement () .appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "head")); aHead.appendChild (aDoc.createTextNode ("Hallo")); final Element aBody = (Element) aDoc.getDocumentElement () .appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "body")); aBody.appendChild (aDoc.createElementNS (DOCTYPE_XHTML10_URI, "img")); // test including doc type final String sResult = XMLWriter.getNodeAsString (aDoc, XMLWriterSettings.createForHTML4 ()); assertEquals ("<!DOCTYPE html PUBLIC \"" + DOCTYPE_XHTML10_QNAME + "\" \"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + "<html xmlns=\"" + DOCTYPE_XHTML10_URI + "\">" + CRLF + sINDENT + "<head>Hallo</head>" + CRLF + sINDENT + "<body>" + CRLF + sINDENT + sINDENT + // Unclosed img :) "<img>" + CRLF + sINDENT + "</body>" + CRLF + "</html>" + CRLF, sResult); }
Example #24
Source File: CollectingTransformErrorListenerTest.java From ph-commons with Apache License 2.0 | 4 votes |
@Test public void testSecure () throws TransformerConfigurationException, TransformerException { final CollectingTransformErrorListener el = new CollectingTransformErrorListener (); final TransformerFactory fac = XMLTransformerFactory.createTransformerFactory (el.andThen (new LoggingTransformErrorListener (L_EN)), new LoggingTransformURIResolver ()); assertNotNull (fac); // "file" access is needed for the tests XMLTransformerFactory.makeTransformerFactorySecure (fac, "file"); // Read valid XSLT Templates t1 = XMLTransformerFactory.newTemplates (fac, new ClassPathResource ("xml/test1.xslt")); assertNotNull (t1); // May contain warning in JDK 1.7 // (http://javax.xml.XMLConstants/property/accessExternalDTD is unknown) assertTrue (el.getErrorList ().containsNoError ()); // Try a real transformation { final Document aDoc = XMLFactory.newDocument (); t1.newTransformer () .transform (TransformSourceFactory.create (new ClassPathResource ("xml/xslt1.xml")), new DOMResult (aDoc)); assertNotNull (aDoc); assertNotNull (aDoc.getDocumentElement ()); assertEquals ("html", aDoc.getDocumentElement ().getTagName ()); } // Read valid XSLT (with import) t1 = XMLTransformerFactory.newTemplates (fac, new ClassPathResource ("xml/test2.xslt")); assertNotNull (t1); // May contain warning in JDK 1.7 // (http://javax.xml.XMLConstants/property/accessExternalDTD is unknown) assertTrue (el.getErrorList ().containsNoError ()); // Read invalid XSLT assertNull (XMLTransformerFactory.newTemplates (fac, new ClassPathResource ("test1.txt"))); assertTrue (el.getErrorList ().containsAtLeastOneError ()); CommonsTestHelper.testToStringImplementation (el); }
Example #25
Source File: XMLWriterTest.java From ph-commons with Apache License 2.0 | 4 votes |
@Test public void testWithNamespaceContext () { final Document aDoc = XMLFactory.newDocument (); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS ("ns1url", "root")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child1")); eRoot.appendChild (aDoc.createElementNS ("ns2url", "child2")); final XMLWriterSettings aSettings = new XMLWriterSettings ().setCharset (StandardCharsets.ISO_8859_1) .setIndent (EXMLSerializeIndent.NONE); String s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + "<root xmlns=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" />" + "</root>", s); final MapBasedNamespaceContext aCtx = new MapBasedNamespaceContext (); aCtx.addMapping ("a", "ns1url"); aSettings.setNamespaceContext (aCtx); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + "<a:root xmlns:a=\"ns1url\">" + "<ns0:child1 xmlns:ns0=\"ns2url\" />" + "<ns0:child2 xmlns:ns0=\"ns2url\" />" + "</a:root>", s); aCtx.addMapping ("xy", "ns2url"); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + "<a:root xmlns:a=\"ns1url\">" + "<xy:child1 xmlns:xy=\"ns2url\" />" + "<xy:child2 xmlns:xy=\"ns2url\" />" + "</a:root>", s); aSettings.setUseDoubleQuotesForAttributes (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='no'?>" + "<a:root xmlns:a='ns1url'>" + "<xy:child1 xmlns:xy='ns2url' />" + "<xy:child2 xmlns:xy='ns2url' />" + "</a:root>", s); aSettings.setSpaceOnSelfClosedElement (false); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='no'?>" + "<a:root xmlns:a='ns1url'>" + "<xy:child1 xmlns:xy='ns2url'/>" + "<xy:child2 xmlns:xy='ns2url'/>" + "</a:root>", s); aSettings.setPutNamespaceContextPrefixesInRoot (true); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='no'?>" + "<a:root xmlns:a='ns1url' xmlns:xy='ns2url'>" + "<xy:child1/>" + "<xy:child2/>" + "</a:root>", s); eRoot.appendChild (aDoc.createElementNS ("ns3url", "zz")); s = XMLWriter.getNodeAsString (aDoc, aSettings); assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='no'?>" + "<a:root xmlns:a='ns1url' xmlns:xy='ns2url'>" + "<xy:child1/>" + "<xy:child2/>" + "<ns0:zz xmlns:ns0='ns3url'/>" + "</a:root>", s); }
Example #26
Source File: XMLTransformerFactoryTest.java From ph-commons with Apache License 2.0 | 4 votes |
@Test public void testSpecialChars () throws Exception { final EXMLVersion eXMLVersion = EXMLVersion.XML_10; final EXMLSerializeVersion eXMLSerializeVersion = EXMLSerializeVersion.getFromXMLVersionOrThrow (eXMLVersion); final StringBuilder aAttrVal = new StringBuilder (); final StringBuilder aText = new StringBuilder (); for (char i = 0; i < 256; ++i) { if (!XMLCharHelper.isInvalidXMLAttributeValueChar (eXMLSerializeVersion, i)) aAttrVal.append (i); if (!XMLCharHelper.isInvalidXMLTextChar (eXMLSerializeVersion, i)) aText.append (i); } final Document aDoc = XMLFactory.newDocument (eXMLVersion); final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root")); eRoot.setAttribute ("test", aAttrVal.toString ()); final Element e1 = (Element) eRoot.appendChild (aDoc.createElement ("a")); e1.appendChild (aDoc.createTextNode (aText.toString ())); final Element e2 = (Element) eRoot.appendChild (aDoc.createElement ("b")); e2.appendChild (aDoc.createCDATASection ("aaaaaaaaaaa]]>bbbbbbbbbbb]]>ccccccccc")); final Element e3 = (Element) eRoot.appendChild (aDoc.createElement ("c")); e3.appendChild (aDoc.createCDATASection ("]]>")); if (false) e3.appendChild (aDoc.createComment ("<!--")); e3.appendChild (aDoc.createTextNode ("abc")); if (false) e3.appendChild (aDoc.createComment ("-->")); final NonBlockingStringWriter aSW = new NonBlockingStringWriter (); XMLTransformerFactory.newTransformer ().transform (new DOMSource (aDoc), new StreamResult (aSW)); final String sTransform = aSW.getAsString (); final Document aDoc2 = DOMReader.readXMLDOM (sTransform); final Node e3a = aDoc2.getDocumentElement ().getChildNodes ().item (2); aSW.reset (); XMLTransformerFactory.newTransformer ().transform (new DOMSource (e3a), new StreamResult (aSW)); final String sXML = XMLWriter.getNodeAsString (aDoc, new XMLWriterSettings ().setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.WRITE_TO_FILE_NO_LOG) .setIndent (EXMLSerializeIndent.NONE)); assertNotNull (sXML); assertNotNull ("Failed to read: " + sXML, DOMReader.readXMLDOM (sXML)); }