private void saveDocumentTo() throws XMLException { try { TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transf = tfactory.newTransformer(); transf.setOutputProperty( OutputKeys.INDENT, "yes" ); transf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transf.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "no" ); transf.setOutputProperty( OutputKeys.METHOD, "xml" ); DOMImplementation impl = doc.getImplementation(); DocumentType doctype = impl.createDocumentType( "doctype", "-//Recordare//DTD MusicXML 3.0 Partwise//EN", "http://www.musicxml.org/dtds/partwise.dtd" ); transf.setOutputProperty( OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId() ); transf.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId() ); DOMSource src = new DOMSource( doc ); StreamResult resultS = new StreamResult( file ); transf.transform( src, resultS ); } catch ( TransformerException e ) { throw new XMLException( "Could not save the File" ); } }
private static DocumentType getDocumentType(Document doc) { DOMImplementation domImpl = doc.getImplementation(); // <!DOCTYPE datafile PUBLIC "-//Logiqx//DTD ROM Management Datafile//EN" "http://www.logiqx.com/Dats/datafile.dtd"> DocumentType doctype = domImpl.createDocumentType("datafile", "-//Logiqx//DTD ROM Management Datafile//EN", "http://www.logiqx.com/Dats/datafile.dtd"); return doctype; }
/** Test that read/write DOCTYPE works too. */ public void testDocType() throws Exception { String data = "<!DOCTYPE foo PUBLIC \"The foo DTD\" \"http://nowhere.net/foo.dtd\"><foo><x/><x/></foo>"; Document doc = XMLUtil.parse(new InputSource(new StringReader(data)), true, true, new Handler(), new Resolver()); DocumentType t = doc.getDoctype(); assertNotNull(t); assertEquals("foo", t.getName()); assertEquals("The foo DTD", t.getPublicId()); assertEquals("http://nowhere.net/foo.dtd", t.getSystemId()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLUtil.write(doc, baos, "UTF-8"); String data2 = baos.toString("UTF-8"); //System.err.println("data2:\n" + data2); assertTrue(data2, data2.indexOf("foo") != -1); assertTrue(data2, data2.indexOf('x') != -1); assertTrue(data2, data2.indexOf("DOCTYPE") != -1); assertTrue(data2, data2.indexOf("The foo DTD") != -1); assertTrue(data2, data2.indexOf("http://nowhere.net/foo.dtd") != -1); }
public static void write(Document doc, OutputStream out) throws IOException { // XXX note that this may fail to write out namespaces correctly if the document // is created with namespaces and no explicit prefixes; however no code in // this package is likely to be doing so try { Transformer t = TransformerFactory.newInstance().newTransformer( new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT))); DocumentType dt = doc.getDoctype(); if (dt != null) { String pub = dt.getPublicId(); if (pub != null) { t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub); } t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dt.getSystemId()); } t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N Source source = new DOMSource(doc); Result result = new StreamResult(out); t.transform(source, result); } catch (Exception | TransformerFactoryConfigurationError e) { throw new IOException(e); } }
/** * Write. * * @param node * the node * @throws ShellException * the shell exception */ protected void write(DocumentType node) throws ShellException { printWriter.print("<!DOCTYPE "); //$NON-NLS-1$ printWriter.print(node.getName()); String publicId = node.getPublicId(); String systemId = node.getSystemId(); if (publicId != null) { printWriter.print(" PUBLIC \""); //$NON-NLS-1$ printWriter.print(publicId); printWriter.print("\" \""); //$NON-NLS-1$ printWriter.print(systemId); printWriter.print('\"'); } else if (systemId != null) { printWriter.print(" SYSTEM \""); //$NON-NLS-1$ printWriter.print(systemId); printWriter.print('"'); } String internalSubset = node.getInternalSubset(); if (internalSubset != null) { printWriter.println(" ["); //$NON-NLS-1$ printWriter.print(internalSubset); printWriter.print(']'); } printWriter.println('>'); }
protected void write(DocumentType node) throws ShellException { printWriter.print("<!DOCTYPE "); //$NON-NLS-1$ printWriter.print(node.getName()); String publicId = node.getPublicId(); String systemId = node.getSystemId(); if (publicId != null) { printWriter.print(" PUBLIC \""); //$NON-NLS-1$ printWriter.print(publicId); printWriter.print("\" \""); //$NON-NLS-1$ printWriter.print(systemId); printWriter.print('\"'); } else if (systemId != null) { printWriter.print(" SYSTEM \""); //$NON-NLS-1$ printWriter.print(systemId); printWriter.print('"'); } String internalSubset = node.getInternalSubset(); if (internalSubset != null) { printWriter.println(" ["); //$NON-NLS-1$ printWriter.print(internalSubset); printWriter.print(']'); } printWriter.println('>'); }
/** * Returns the document type public identifier * specified for this document, or null. */ public static String whichDoctypePublic( Document doc ) { DocumentType doctype; /* DOM Level 2 was introduced into the code base*/ doctype = doc.getDoctype(); if ( doctype != null ) { // Note on catch: DOM Level 1 does not specify this method // and the code will throw a NoSuchMethodError try { return doctype.getPublicId(); } catch ( Error except ) { } } if ( doc instanceof HTMLDocument ) return DTD.XHTMLPublicId; return null; }
/** * Returns the document type system identifier * specified for this document, or null. */ public static String whichDoctypeSystem( Document doc ) { DocumentType doctype; /* DOM Level 2 was introduced into the code base*/ doctype = doc.getDoctype(); if ( doctype != null ) { // Note on catch: DOM Level 1 does not specify this method // and the code will throw a NoSuchMethodError try { return doctype.getSystemId(); } catch ( Error except ) { } } if ( doc instanceof HTMLDocument ) return DTD.XHTMLSystemId; return null; }
public static void saveXMLDoctoFile(Document doc, DocumentType documentType, String path) throws TransformerException { // Save DOM XML doc to File TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); doc.setXmlVersion("1.0"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, documentType.getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, documentType.getSystemId()); transformer.transform(new DOMSource(doc), new StreamResult(new File(path))); }
public static void saveDATtoFile(Datafile datafile, String path) throws ParserConfigurationException, JAXBException, TransformerException, FileNotFoundException { JAXBContext jc = JAXBContext.newInstance(Datafile.class); // Create the Document DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.newDocument(); DocumentType docType = getDocumentType(document); // Marshal the Object to a Document formatted so human readable Marshaller marshaller = jc.createMarshaller(); /* marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, docType.getSystemId()); */ marshaller.marshal(datafile, document); document.setXmlStandalone(true); // NOTE could output with marshaller but cannot set DTD document type /* OutputStream os = new FileOutputStream(path); marshaller.marshal(datafile, os); */ // Output the Document TransformerFactory transformerFactory = TransformerFactory.newInstance(); // transformerFactory.setAttribute("indent-number", "4"); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "8"); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId()); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File(path)); transformer.transform(source, result); }
/** * End processing of given node * * * @param node Node we just finished processing * * @throws org.xml.sax.SAXException */ protected void endNode(Node node) throws org.xml.sax.SAXException { switch (node.getNodeType()) { case Node.DOCUMENT_NODE : break; case Node.DOCUMENT_TYPE_NODE : serializeDocType((DocumentType) node, false); break; case Node.ELEMENT_NODE : serializeElement((Element) node, false); break; case Node.CDATA_SECTION_NODE : break; case Node.ENTITY_REFERENCE_NODE : serializeEntityReference((EntityReference) node, false); break; default : } }
/** * A document type declaration information item has the following properties: * * 1. [system identifier] The system identifier of the external subset, if * it exists. Otherwise this property has no value. * * @return the system identifier String object, or null if there is none. */ public String getDocumentTypeDeclarationSystemIdentifier() { Document doc; if (m_root.getNodeType() == Node.DOCUMENT_NODE) doc = (Document) m_root; else doc = m_root.getOwnerDocument(); if (null != doc) { DocumentType dtd = doc.getDoctype(); if (null != dtd) { return dtd.getSystemId(); } } return null; }
/** * Return the public identifier of the external subset, * normalized as described in 4.2.2 External Entities [XML]. If there is * no external subset or if it has no public identifier, this property * has no value. * * @return the public identifier String object, or null if there is none. */ public String getDocumentTypeDeclarationPublicIdentifier() { Document doc; if (m_root.getNodeType() == Node.DOCUMENT_NODE) doc = (Document) m_root; else doc = m_root.getOwnerDocument(); if (null != doc) { DocumentType dtd = doc.getDoctype(); if (null != dtd) { return dtd.getPublicId(); } } return null; }
private void writeDocumentType(DocumentType docType, Writer writer, int depth) throws IOException { String publicId = docType.getPublicId(); String internalSubset = docType.getInternalSubset(); for (int i = 0; i < depth; ++i) { writer.append(' '); } writer.append("<!DOCTYPE ").append(docType.getName()); if (publicId != null) { writer.append(" PUBLIC '").append(publicId).append("' "); } else { writer.write(" SYSTEM "); } writer.append("'").append(docType.getSystemId()).append("'"); if (internalSubset != null) { writer.append(" [").append(internalSubset).append("]"); } writer.append('>').append(lineSeparator); }
/** * <b>DOM</b>: Implements {@link * DOMImplementation#createDocumentType(String,String,String)}. */ public DocumentType createDocumentType(String qualifiedName, String publicId, String systemId) { if (qualifiedName == null) { qualifiedName = ""; } int test = XMLUtilities.testXMLQName(qualifiedName); if ((test & XMLUtilities.IS_XML_10_NAME) == 0) { throw new DOMException (DOMException.INVALID_CHARACTER_ERR, formatMessage("xml.name", new Object[] { qualifiedName })); } if ((test & XMLUtilities.IS_XML_10_QNAME) == 0) { throw new DOMException (DOMException.INVALID_CHARACTER_ERR, formatMessage("invalid.qname", new Object[] { qualifiedName })); } return new GenericDocumentType(qualifiedName, publicId, systemId); }
public Node replaceChild(Node newChild, Node oldChild) throws DOMException { if (newChild instanceof StandaloneDocumentType) { DocumentType dt = (DocumentType) newChild; newChild = ((GnomeDocument) getOwnerDocument()) .createDocumentType(dt.getName(), dt.getPublicId(), dt.getSystemId()); } if (newChild == null) { throw new GnomeDOMException(DOMException.NOT_FOUND_ERR, null); } if (!(newChild instanceof GnomeNode)) { throw new GnomeDOMException(DOMException.WRONG_DOCUMENT_ERR, newChild.toString()); } if (oldChild == null || !(oldChild instanceof GnomeNode)) { throw new GnomeDOMException(DOMException.NOT_FOUND_ERR, null); } return xmljReplaceChild(newChild, oldChild); }
public Node appendChild(Node newChild) throws DOMException { if (newChild instanceof StandaloneDocumentType) { DocumentType dt = (DocumentType) newChild; newChild = ((GnomeDocument) getOwnerDocument()) .createDocumentType(dt.getName(), dt.getPublicId(), dt.getSystemId()); } if (!(newChild instanceof GnomeNode)) { throw new GnomeDOMException(DOMException.WRONG_DOCUMENT_ERR, null); } return xmljAppendChild(newChild); }
/** * {@inheritDoc} * @since TFP 1.0 */ public void write (final Document document) { DocumentType doctype = document.getDoctype (); output.print ("<?xml version=\"1.0\" encoding=\"" + getEncoding () + "\"?>"); if (doctype != null) { output.print ("<!DOCTYPE " + doctype.getName ()); if (doctype.getPublicId () != null) { output.print (" PUBLIC \"" + doctype.getPublicId () + "\""); output.print (" \"" + doctype.getSystemId () +"\""); } else if (doctype.getSystemId () != null) output.print (" SYSTEM \"" + doctype.getSystemId () + "\""); if (doctype.getInternalSubset () != null) { output.print (" ["); output.print (doctype.getInternalSubset ()); } output.print (">"); } write (document.getDocumentElement ()); }
/** * {@inheritDoc} * @since TFP 1.0 */ public void write (Document document) { DocumentType doctype = document.getDoctype (); output.println ("<?xml version=\"1.0\" encoding=\"" + getEncoding () + "\"?>"); if (doctype != null) { output.print ("<!DOCTYPE " + doctype.getName ()); if (doctype.getPublicId () != null) { output.print (" PUBLIC \"" + doctype.getPublicId () + "\""); output.print (" \"" + doctype.getSystemId () +"\""); } else if (doctype.getSystemId () != null) output.print (" SYSTEM \"" + doctype.getSystemId () + "\""); if (doctype.getInternalSubset () != null) { output.println (" ["); output.println (doctype.getInternalSubset ()); output.print ("]"); } output.println (">"); } write (document.getDocumentElement ()); }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getDoctype") && args == null) { // NOI18N return (DocumentType)proxyDocument; } else if (method.getName().equals("getPublicId") && args == null) { // NOI18N Document d = getDocumentImpl(false); if (d != null) { DocumentType doctype = d.getDoctype(); return doctype == null ? null : doctype.getPublicId(); } else { return obj.getIP().getPublicId(); } } else { return method.invoke(getDocumentImpl(true), args); } }
/** * The getUnparsedEntityURI function returns the URI of the unparsed * entity with the specified name in the same document as the context * node (see [3.3 Unparsed Entities]). It returns the empty string if * there is no such entity. */ public String getUnparsedEntityURI(String name) { // Special handling for DOM input if (_document != null) { String uri = ""; DocumentType doctype = _document.getDoctype(); if (doctype != null) { NamedNodeMap entities = doctype.getEntities(); if (entities == null) { return uri; } Entity entity = (Entity) entities.getNamedItem(name); if (entity == null) { return uri; } String notationName = entity.getNotationName(); if (notationName != null) { uri = entity.getSystemId(); if (uri == null) { uri = entity.getPublicId(); } } } return uri; } else { return super.getUnparsedEntityURI(name); } }
/** For DOM2 support. */ public CoreDocumentImpl(DocumentType doctype, boolean grammarAccess) { this(grammarAccess); if (doctype != null) { DocumentTypeImpl doctypeImpl; try { doctypeImpl = (DocumentTypeImpl) doctype; } catch (ClassCastException e) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null); throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, msg); } doctypeImpl.ownerDocument = this; appendChild(doctype); } }
/** * For XML, this provides access to the Document Type Definition. * For HTML documents, and XML documents which don't specify a DTD, * it will be null. */ public DocumentType getDoctype() { if (needsSyncChildren()) { synchronizeChildren(); } return docType; }
/** * Returns the absolute base URI of this node or null if the implementation * wasn't able to obtain an absolute URI. Note: If the URI is malformed, a * null is returned. * * @return The absolute base URI of this node or null. * @since DOM Level 3 */ public String getBaseURI() { if (needsSyncData()) { synchronizeData(); } if (baseURI == null) { DocumentType doctype; NamedNodeMap entities; EntityImpl entDef; if (null != (doctype = getOwnerDocument().getDoctype()) && null != (entities = doctype.getEntities())) { entDef = (EntityImpl)entities.getNamedItem(getNodeName()); if (entDef !=null) { return entDef.getBaseURI(); } } } else if (baseURI != null && baseURI.length() != 0 ) {// attribute value is always empty string try { return new URI(baseURI).toString(); } catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException e){ // REVISIT: what should happen in this case? return null; } } return baseURI; }
/** * EntityReference's children are a reflection of those defined in the * named Entity. This method creates them if they haven't been created yet. * This doesn't support editing the Entity though, since this only called * once for all. */ protected void synchronizeChildren() { // no need to synchronize again needsSyncChildren(false); DocumentType doctype; NamedNodeMap entities; EntityImpl entDef; if (null != (doctype = getOwnerDocument().getDoctype()) && null != (entities = doctype.getEntities())) { entDef = (EntityImpl)entities.getNamedItem(getNodeName()); // No Entity by this name, stop here. if (entDef == null) return; // If entity's definition exists, clone its kids isReadOnly(false); for (Node defkid = entDef.getFirstChild(); defkid != null; defkid = defkid.getNextSibling()) { Node newkid = defkid.cloneNode(true); insertBefore(newkid, null); } setReadOnly(true, true); } }
/** * Extracts NamedNodeMap of entities. We need this to validate * elements and attributes of type xs:ENTITY, xs:ENTITIES or * types dervied from them. */ private void setupEntityMap(Document doc) { if (doc != null) { DocumentType docType = doc.getDoctype(); if (docType != null) { fEntities = docType.getEntities(); return; } } fEntities = null; }
public void doctypeDecl(DocumentType node) throws XNIException { /** Create new DocumentType node for the target. */ if (fDocumentImpl != null) { DocumentType docType = fDocumentImpl.createDocumentType(node.getName(), node.getPublicId(), node.getSystemId()); final String internalSubset = node.getInternalSubset(); /** Copy internal subset. */ if (internalSubset != null) { ((DocumentTypeImpl) docType).setInternalSubset(internalSubset); } /** Copy entities. */ NamedNodeMap oldMap = node.getEntities(); NamedNodeMap newMap = docType.getEntities(); int length = oldMap.getLength(); for (int i = 0; i < length; ++i) { Entity oldEntity = (Entity) oldMap.item(i); EntityImpl newEntity = (EntityImpl) fDocumentImpl.createEntity(oldEntity.getNodeName()); newEntity.setPublicId(oldEntity.getPublicId()); newEntity.setSystemId(oldEntity.getSystemId()); newEntity.setNotationName(oldEntity.getNotationName()); newMap.setNamedItem(newEntity); } /** Copy notations. */ oldMap = node.getNotations(); newMap = docType.getNotations(); length = oldMap.getLength(); for (int i = 0; i < length; ++i) { Notation oldNotation = (Notation) oldMap.item(i); NotationImpl newNotation = (NotationImpl) fDocumentImpl.createNotation(oldNotation.getNodeName()); newNotation.setPublicId(oldNotation.getPublicId()); newNotation.setSystemId(oldNotation.getSystemId()); newMap.setNamedItem(newNotation); } append(docType); } }
/** * Unimplemented. See org.w3c.dom.Document * * @return null */ public DocumentType getDoctype() { error(XMLErrorResources.ER_FUNCTION_NOT_SUPPORTED); return null; }