下面列出了怎么用org.w3c.dom.DocumentType的API类实例代码及写法,或者点击链接到github查看源代码。
private void initialize(Document d, SAXParseException saxEx, String defaultPublicId) {
document = d;
saxException = saxEx;
documentInfo = null;
// TODO Handle default version better.
version = "unknown"; // NOI18N
// first check the doc type to see if there is one
DocumentType dt = document.getDoctype();
if (dt != null) {
documentInfo = publicIdToInfoMap.get(dt.getPublicId());
} else if (defaultPublicId != null) {
documentInfo = publicIdToInfoMap.get(defaultPublicId);
}
if (documentInfo != null) {
version = documentInfo.getVersion();
}
}
public static List<Node> getNodeList(final String key, final Node parentNode) {
final List<Node> nodes = new ArrayList<>();
final NodeList childNodes = parentNode.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
final Node childNode = childNodes.item(i);
if (childNode.getNodeName().equals(key)) {
// ignore node generated from DOCTYPE declaration
if (childNode instanceof DocumentType) {
Node nextSibling = childNode.getNextSibling();
if (nextSibling.getNodeName().equals(key)) {
nodes.add(nextSibling);
}
} else {
nodes.add(childNode);
}
}
}
return nodes;
}
protected static void appendDocumentTypeDetail(StringBuffer buf, Node aNode) {
DocumentType type = (DocumentType) aNode;
buf.append(XMLConstants.START_DOCTYPE).append(type.getName());
boolean hasNoPublicId = true;
if (type.getPublicId()!=null
&& type.getPublicId().length() > 0) {
buf.append(" PUBLIC \"").append(type.getPublicId())
.append('"');
hasNoPublicId = false;
}
if (type.getSystemId()!=null
&& type.getSystemId().length() > 0) {
if (hasNoPublicId) {
buf.append(" SYSTEM");
}
buf.append(" \"").append(type.getSystemId())
.append('"');
}
}
/**
* Appends the XML DOCTYPE for {@link #getShortString} or {@link #appendFullDocumentHeader} if present.
*
* @param sb the builder to append to
* @param type the document type
* @return true if the DOCTPYE has been appended
*
* @since XMLUnit 2.4.0
*/
protected boolean appendDocumentType(StringBuilder sb, DocumentType type) {
if (type == null) {
return false;
}
sb.append("<!DOCTYPE ").append(type.getName());
boolean hasNoPublicId = true;
if (type.getPublicId() != null && type.getPublicId().length() > 0) {
sb.append(" PUBLIC \"").append(type.getPublicId()).append('"');
hasNoPublicId = false;
}
if (type.getSystemId() != null && type.getSystemId().length() > 0) {
if (hasNoPublicId) {
sb.append(" SYSTEM");
}
sb.append(" \"").append(type.getSystemId()).append("\"");
}
sb.append(">");
return true;
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* Unimplemented. See org.w3c.dom.Document
*
* @return null
*/
public DocumentType getDoctype()
{
error(XMLErrorResources.ER_FUNCTION_NOT_SUPPORTED);
return null;
}
/**
* 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);
}
}
/**
* Recursively appends a {@link Node} child to {@link DomNode} parent.
*
* @param page the owner page of {@link DomElement}s to be created
* @param parent the parent DomNode
* @param child the child Node
* @param handleXHTMLAsHTML if true elements from the XHTML namespace are handled as HTML elements instead of
* DOM elements
* @param attributesOrderMap (optional) the one returned by {@link #getAttributesOrderMap(Document)}
*/
public static void appendChild(final SgmlPage page, final DomNode parent, final Node child,
final boolean handleXHTMLAsHTML, final Map<Integer, List<String>> attributesOrderMap) {
final DocumentType documentType = child.getOwnerDocument().getDoctype();
if (documentType != null && page instanceof XmlPage) {
final DomDocumentType domDoctype = new DomDocumentType(
page, documentType.getName(), documentType.getPublicId(), documentType.getSystemId());
((XmlPage) page).setDocumentType(domDoctype);
}
final DomNode childXml = createFrom(page, child, handleXHTMLAsHTML, attributesOrderMap);
parent.appendChild(childXml);
copy(page, child, childXml, handleXHTMLAsHTML, attributesOrderMap);
}
/**
* 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;
}
/**
* Get a string representation of a doctype element and append it to a {@code builder}.
* @param builder a string builder to write result to.
* @param documentType a doctype element.
*/
public static void toString(StringBuilder builder, DocumentType documentType) {
builder.append("<!DOCTYPE ").append(documentType.getName());
if (StringUtils.isNotBlank(documentType.getPublicId())) {
builder.append(" PUBLIC \"").append(documentType.getPublicId()).append('"');
}
if (StringUtils.isNotBlank(documentType.getSystemId())) {
builder.append(" \"").append(documentType.getSystemId()).append('"');
}
builder.append('>');
}
/**
* 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);
}
}
/**
* Recursively appends a {@link Node} child to {@link DomNode} parent.
*
* @param page the owner page of {@link DomElement}s to be created
* @param parent the parent DomNode
* @param child the child Node
* @param handleXHTMLAsHTML if true elements from the XHTML namespace are handled as HTML elements instead of
* DOM elements
* @param attributesOrderMap (optional) the one returned by {@link #getAttributesOrderMap(Document)}
*/
public static void appendChild(final SgmlPage page, final DomNode parent, final Node child,
final boolean handleXHTMLAsHTML, final Map<Integer, List<String>> attributesOrderMap) {
final DocumentType documentType = child.getOwnerDocument().getDoctype();
if (documentType != null && page instanceof XmlPage) {
final DomDocumentType domDoctype = new DomDocumentType(
page, documentType.getName(), documentType.getPublicId(), documentType.getSystemId());
((XmlPage) page).setDocumentType(domDoctype);
}
final DomNode childXml = createFrom(page, child, handleXHTMLAsHTML, attributesOrderMap);
parent.appendChild(childXml);
copy(page, child, childXml, handleXHTMLAsHTML, attributesOrderMap);
}
/**
* @return version of deployment descriptor.
*/
private void extractVersion () {
// This is the default version
version = Application.VERSION_7;
// first check the doc type to see if there is one
DocumentType dt = document.getDoctype();
if(dt == null) {
//check application node version attribute
NodeList nl = document.getElementsByTagName("application");//NOI18N
if(nl != null && nl.getLength() > 0) {
Node appNode = nl.item(0);
NamedNodeMap attrs = appNode.getAttributes();
Node vNode = attrs.getNamedItem("version");//NOI18N
if(vNode != null) {
String versionValue = vNode.getNodeValue();
if (Application.VERSION_1_4.equals(versionValue)) {
version = Application.VERSION_1_4;
} else if (Application.VERSION_5.equals(versionValue)) {
version = Application.VERSION_5;
} else if (Application.VERSION_6.equals(versionValue)) {
version = Application.VERSION_6;
} else {
version = Application.VERSION_7; //default
}
}
}
}
}
private static Document createPrefsDoc( String qname ) {
try {
DOMImplementation di = DocumentBuilderFactory.newInstance().
newDocumentBuilder().getDOMImplementation();
DocumentType dt = di.createDocumentType(qname, null, PREFS_DTD_URI);
return di.createDocument(null, qname, dt);
} catch(ParserConfigurationException e) {
throw new AssertionError(e);
}
}
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;
}
private static boolean belongsToProlog(Node n,
boolean ignoreDoctypeDeclarationAsWell) {
if (n == null || n instanceof Element) {
return false;
}
if (!ignoreDoctypeDeclarationAsWell && n instanceof DocumentType) {
return false;
}
if (n instanceof Document) {
return true;
}
return belongsToProlog(n.getParentNode(), ignoreDoctypeDeclarationAsWell);
}
/** 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;
}
@Test
public void testCreateDocumentType02() throws ParserConfigurationException {
final String name = "document:localName";
final String publicId = "-//W3C//DTD HTML 4.0 Transitional//EN";
final String systemId = "http://www.w3.org/TR/REC-html40/loose.dtd";
DOMImplementation domImpl = getDOMImplementation();
DocumentType documentType = domImpl.createDocumentType(name, publicId, systemId);
Document document = domImpl.createDocument("http://www.document.com", "document:localName", documentType);
verifyDocumentType(document.getDoctype(), name, publicId, systemId);
}
/**
* 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;
}
/** 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);
}
}
/**
* Introduced in DOM Level 2. <p>
*
* Creates an XML Document object of the specified type with its document
* element.
*
* @param namespaceURI The namespace URI of the document
* element to create, or null.
* @param qualifiedName The qualified name of the document
* element to create.
* @param doctype The type of document to be created or null.<p>
*
* When doctype is not null, its
* Node.ownerDocument attribute is set to
* the document being created.
* @return Document A new Document object.
* @throws DOMException WRONG_DOCUMENT_ERR: Raised if doctype has
* already been used with a different document.
* @since WD-DOM-Level-2-19990923
*/
public Document createDocument(String namespaceURI,
String qualifiedName,
DocumentType doctype)
throws DOMException
{
if (doctype != null && doctype.getOwnerDocument() != null) {
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.XML_DOMAIN,
"WRONG_DOCUMENT_ERR", null));
}
DocumentImpl doc = new PSVIDocumentImpl(doctype);
Element e = doc.createElementNS( namespaceURI, qualifiedName);
doc.appendChild(e);
return doc;
}
@Override
public DocumentType createDocumentType(String qualifiedName,String publicId, String systemId)
{
throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR);
}
/**
* Introduced in DOM Level 2. <p>
*
* Creates an XML Document object of the specified type with its document
* element.
*
* @param namespaceURI The namespace URI of the document
* element to create, or null.
* @param qualifiedName The qualified name of the document
* element to create.
* @param doctype The type of document to be created or null.<p>
*
* When doctype is not null, its
* Node.ownerDocument attribute is set to
* the document being created.
* @return Document A new Document object.
* @throws DOMException WRONG_DOCUMENT_ERR: Raised if doctype has
* already been used with a different document.
* @since WD-DOM-Level-2-19990923
*/
public Document createDocument(String namespaceURI,
String qualifiedName,
DocumentType doctype)
throws DOMException
{
if (doctype != null && doctype.getOwnerDocument() != null) {
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.XML_DOMAIN,
"WRONG_DOCUMENT_ERR", null));
}
DocumentImpl doc = new PSVIDocumentImpl(doctype);
Element e = doc.createElementNS( namespaceURI, qualifiedName);
doc.appendChild(e);
return doc;
}
/**
* 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.
* <p>
* XML processors may choose to use the System Identifier (if one
* is provided) to resolve the entity, rather than the URI in the
* Public Identifier. The details are dependent on the processor, and
* we would have to support some form of plug-in resolver to handle
* this properly. Currently, we simply return the System Identifier if
* present, and hope that it a usable URI or that our caller can
* map it to one.
* TODO: Resolve Public Identifiers... or consider changing function name.
* <p>
* If we find a relative URI
* reference, XML expects it to be resolved in terms of the base URI
* of the document. The DOM doesn't do that for us, and it isn't
* entirely clear whether that should be done here; currently that's
* pushed up to a higher level of our application. (Note that DOM Level
* 1 didn't store the document's base URI.)
* TODO: Consider resolving Relative URIs.
* <p>
* (The DOM's statement that "An XML processor may choose to
* completely expand entities before the structure model is passed
* to the DOM" refers only to parsed entities, not unparsed, and hence
* doesn't affect this function.)
*
* @param name A string containing the Entity Name of the unparsed
* entity.
*
* @return String containing the URI of the Unparsed Entity, or an
* empty string if no such entity exists.
*/
public String getUnparsedEntityURI(String name)
{
String url = "";
Document doc = (m_root.getNodeType() == Node.DOCUMENT_NODE)
? (Document) m_root : m_root.getOwnerDocument();
if (null != doc)
{
DocumentType doctype = doc.getDoctype();
if (null != doctype)
{
NamedNodeMap entities = doctype.getEntities();
if(null == entities)
return url;
Entity entity = (Entity) entities.getNamedItem(name);
if(null == entity)
return url;
String notationName = entity.getNotationName();
if (null != notationName) // then it's unparsed
{
// The draft says: "The XSLT processor may use the public
// identifier to generate a URI for the entity instead of the URI
// specified in the system identifier. If the XSLT processor does
// not use the public identifier to generate the URI, it must use
// the system identifier; if the system identifier is a relative
// URI, it must be resolved into an absolute URI using the URI of
// the resource containing the entity declaration as the base
// URI [RFC2396]."
// So I'm falling a bit short here.
url = entity.getSystemId();
if (null == url)
{
url = entity.getPublicId();
}
else
{
// This should be resolved to an absolute URL, but that's hard
// to do from here.
}
}
}
}
return url;
}
private static DomNode createFrom(final SgmlPage page, final Node source, final boolean handleXHTMLAsHTML,
final Map<Integer, List<String>> attributesOrderMap) {
if (source.getNodeType() == Node.TEXT_NODE) {
return new DomText(page, source.getNodeValue());
}
if (source.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
return new DomProcessingInstruction(page, source.getNodeName(), source.getNodeValue());
}
if (source.getNodeType() == Node.COMMENT_NODE) {
return new DomComment(page, source.getNodeValue());
}
if (source.getNodeType() == Node.DOCUMENT_TYPE_NODE) {
final DocumentType documentType = (DocumentType) source;
return new DomDocumentType(page, documentType.getName(), documentType.getPublicId(),
documentType.getSystemId());
}
final String ns = source.getNamespaceURI();
String localName = source.getLocalName();
if (handleXHTMLAsHTML && HTMLParser.XHTML_NAMESPACE.equals(ns)) {
final ElementFactory factory = HTMLParser.getFactory(localName);
return factory.createElementNS(page, ns, localName,
namedNodeMapToSaxAttributes(source.getAttributes(), attributesOrderMap, source));
}
final NamedNodeMap nodeAttributes = source.getAttributes();
if (page != null && page.isHtmlPage()) {
localName = localName.toUpperCase(Locale.ROOT);
}
final String qualifiedName;
if (source.getPrefix() == null) {
qualifiedName = localName;
}
else {
qualifiedName = source.getPrefix() + ':' + localName;
}
final String namespaceURI = source.getNamespaceURI();
if (HTMLParser.SVG_NAMESPACE.equals(namespaceURI)) {
return HTMLParser.SVG_FACTORY.createElementNS(page, namespaceURI, qualifiedName,
namedNodeMapToSaxAttributes(nodeAttributes, attributesOrderMap, source));
}
final Map<String, DomAttr> attributes = new LinkedHashMap<>();
for (int i = 0; i < nodeAttributes.getLength(); i++) {
final int orderedIndex = getIndex(nodeAttributes, attributesOrderMap, source, i);
final Attr attribute = (Attr) nodeAttributes.item(orderedIndex);
final String attributeNamespaceURI = attribute.getNamespaceURI();
final String attributeQualifiedName;
if (attribute.getPrefix() != null) {
attributeQualifiedName = attribute.getPrefix() + ':' + attribute.getLocalName();
}
else {
attributeQualifiedName = attribute.getLocalName();
}
final String value = attribute.getNodeValue();
final boolean specified = attribute.getSpecified();
final DomAttr xmlAttribute =
new DomAttr(page, attributeNamespaceURI, attributeQualifiedName, value, specified);
attributes.put(attribute.getNodeName(), xmlAttribute);
}
return new DomElement(namespaceURI, qualifiedName, page, attributes);
}