下面列出了怎么用org.w3c.dom.ProcessingInstruction的API类实例代码及写法,或者点击链接到github查看源代码。
public final void testProcessingInstructionInHtml() {
Document doc = DomParser.makeDocument(null, null);
ProcessingInstruction pi = doc.createProcessingInstruction(
"foo", "<script>alert(1)</script>");
Element el = doc.createElementNS(Namespaces.HTML_NAMESPACE_URI, "div");
el.appendChild(pi);
assertEquals(
"<div><?foo <script>alert(1)</script>?></div>",
Nodes.render(el, MarkupRenderMode.XML));
try {
Nodes.render(el, MarkupRenderMode.HTML);
} catch (UncheckedUnrenderableException ex) {
// OK
return;
}
fail("Rendered in html");
}
private void visit( Node n ) throws SAXException {
setCurrentLocation( n );
// if a case statement gets too big, it should be made into a separate method.
switch(n.getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
String value = n.getNodeValue();
receiver.characters( value.toCharArray(), 0, value.length() );
break;
case Node.ELEMENT_NODE:
visit( (Element)n );
break;
case Node.ENTITY_REFERENCE_NODE:
receiver.skippedEntity(n.getNodeName());
break;
case Node.PROCESSING_INSTRUCTION_NODE:
ProcessingInstruction pi = (ProcessingInstruction)n;
receiver.processingInstruction(pi.getTarget(),pi.getData());
break;
}
}
/**
* Method getStrFromNode
*
* @param xpathnode
* @return the string for the node.
*/
public static String getStrFromNode(Node xpathnode) {
if (xpathnode.getNodeType() == Node.TEXT_NODE) {
// we iterate over all siblings of the context node because eventually,
// the text is "polluted" with pi's or comments
StringBuilder sb = new StringBuilder();
for (Node currentSibling = xpathnode.getParentNode().getFirstChild();
currentSibling != null;
currentSibling = currentSibling.getNextSibling()) {
if (currentSibling.getNodeType() == Node.TEXT_NODE) {
sb.append(((Text) currentSibling).getData());
}
}
return sb.toString();
} else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
return ((Attr) xpathnode).getNodeValue();
} else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
return ((ProcessingInstruction) xpathnode).getNodeValue();
}
return null;
}
/**
* Method getStrFromNode
*
* @param xpathnode
* @return the string for the node.
*/
public static String getStrFromNode(Node xpathnode) {
if (xpathnode.getNodeType() == Node.TEXT_NODE) {
// we iterate over all siblings of the context node because eventually,
// the text is "polluted" with pi's or comments
StringBuilder sb = new StringBuilder();
for (Node currentSibling = xpathnode.getParentNode().getFirstChild();
currentSibling != null;
currentSibling = currentSibling.getNextSibling()) {
if (currentSibling.getNodeType() == Node.TEXT_NODE) {
sb.append(((Text) currentSibling).getData());
}
}
return sb.toString();
} else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
return ((Attr) xpathnode).getNodeValue();
} else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
return ((ProcessingInstruction) xpathnode).getNodeValue();
}
return null;
}
protected void print(Node node, Map namespaces, boolean endWithComma) {
switch (node.getNodeType()) {
case Node.ELEMENT_NODE :
printElement((Element) node, namespaces, endWithComma);
break;
case Node.PROCESSING_INSTRUCTION_NODE :
printPI((ProcessingInstruction) node, endWithComma);
break;
case Node.TEXT_NODE :
printText((Text) node, endWithComma);
break;
case Node.COMMENT_NODE :
printComment((Comment) node, endWithComma);
break;
}
}
private void visit( Node n ) throws SAXException {
setCurrentLocation( n );
// if a case statement gets too big, it should be made into a separate method.
switch(n.getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
String value = n.getNodeValue();
receiver.characters( value.toCharArray(), 0, value.length() );
break;
case Node.ELEMENT_NODE:
visit( (Element)n );
break;
case Node.ENTITY_REFERENCE_NODE:
receiver.skippedEntity(n.getNodeName());
break;
case Node.PROCESSING_INSTRUCTION_NODE:
ProcessingInstruction pi = (ProcessingInstruction)n;
receiver.processingInstruction(pi.getTarget(),pi.getData());
break;
}
}
public void testCompareProcessingInstruction() throws Exception {
String[] expected = PROC_A;
String[] actual = PROC_B;
ProcessingInstruction control = document.createProcessingInstruction(
expected[0], expected[1]);
ProcessingInstruction test = document.createProcessingInstruction(
actual[0], actual[1]);
assertDifferentProcessingInstructions(control, test,
PROCESSING_INSTRUCTION_TARGET);
ProcessingInstruction control2 = document.createProcessingInstruction(
expected[0], expected[1]);
ProcessingInstruction test2 = document.createProcessingInstruction(
expected[0], actual[1]);
assertDifferentProcessingInstructions(control2, test2,
PROCESSING_INSTRUCTION_DATA);
}
private void visit( Node n ) throws SAXException {
setCurrentLocation( n );
// if a case statement gets too big, it should be made into a separate method.
switch(n.getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
String value = n.getNodeValue();
receiver.characters( value.toCharArray(), 0, value.length() );
break;
case Node.ELEMENT_NODE:
visit( (Element)n );
break;
case Node.ENTITY_REFERENCE_NODE:
receiver.skippedEntity(n.getNodeName());
break;
case Node.PROCESSING_INSTRUCTION_NODE:
ProcessingInstruction pi = (ProcessingInstruction)n;
receiver.processingInstruction(pi.getTarget(),pi.getData());
break;
}
}
/**
* {@inheritDoc}
*/
@Override
protected void checkChildHierarchy(final org.w3c.dom.Node newChild) throws DOMException {
if (newChild instanceof Element) {
if (getDocumentElement() != null) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
"The Document may only have a single child Element.");
}
}
else if (newChild instanceof DocumentType) {
if (getDoctype() != null) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
"The Document may only have a single child DocumentType.");
}
}
else if (!(newChild instanceof Comment || newChild instanceof ProcessingInstruction)) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
"The Document may not have a child of this type: " + newChild.getNodeType());
}
super.checkChildHierarchy(newChild);
}
String ecmaValue() {
// TODO See ECMA 357 Section 9.1
if (isTextType()) {
return ((org.w3c.dom.Text)dom).getData();
} else if (isAttributeType()) {
return ((org.w3c.dom.Attr)dom).getValue();
} else if (isProcessingInstructionType()) {
return ((org.w3c.dom.ProcessingInstruction)dom).getData();
} else if (isCommentType()) {
return ((org.w3c.dom.Comment)dom).getNodeValue();
} else if (isElementType()) {
throw new RuntimeException("Unimplemented ecmaValue() for elements.");
} else {
throw new RuntimeException("Unimplemented for node " + dom);
}
}
/**
* is not supported in this release.
* @param target {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeProcessingInstruction(String target) throws XMLStreamException {
if(target == null){
throw new XMLStreamException("Target cannot be null");
}
ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, "");
currentNode.appendChild(pi);
}
private void writeNodePlain(Writer out, Node node, int level) throws FHIRException, DOMException, IOException {
if (node.getNodeType() == Node.ELEMENT_NODE)
writeElementPlain(out, (Element) node, level);
else if (node.getNodeType() == Node.TEXT_NODE)
writeTextPlain(out, (Text) node, level);
else if (node.getNodeType() == Node.COMMENT_NODE)
writeCommentPlain(out, (Comment) node, level);
else if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE)
writeProcessingInstructionPlain(out, (ProcessingInstruction) node);
else if (node.getNodeType() != Node.ATTRIBUTE_NODE)
throw new FHIRException("Unhandled node type");
}
/**
* adds processing instruction node to DOM.
*/
public void processingInstruction(String target, String data) {
appendTextNode();
final Node last = (Node)_nodeStk.peek();
ProcessingInstruction pi = _document.createProcessingInstruction(
target, data);
if (pi != null){
if (last == _root && _nextSibling != null)
last.insertBefore(pi, _nextSibling);
else
last.appendChild(pi);
_lastSibling = pi;
}
}
public void print(Node node) throws XMLStreamException {
switch (node.getNodeType()) {
case Node.DOCUMENT_NODE:
visitDocument((Document) node);
break;
case Node.DOCUMENT_FRAGMENT_NODE:
visitDocumentFragment((DocumentFragment) node);
break;
case Node.ELEMENT_NODE:
visitElement((Element) node);
break;
case Node.TEXT_NODE:
visitText((Text) node);
break;
case Node.CDATA_SECTION_NODE:
visitCDATASection((CDATASection) node);
break;
case Node.PROCESSING_INSTRUCTION_NODE:
visitProcessingInstruction((ProcessingInstruction) node);
break;
case Node.ENTITY_REFERENCE_NODE:
visitReference((EntityReference) node);
break;
case Node.COMMENT_NODE:
visitComment((Comment) node);
break;
case Node.DOCUMENT_TYPE_NODE:
break;
case Node.ATTRIBUTE_NODE:
case Node.ENTITY_NODE:
default:
throw new XMLStreamException("Unexpected DOM Node Type "
+ node.getNodeType()
);
}
}
/**
* adds processing instruction node to DOM.
*/
public void processingInstruction(String target, String data) {
appendTextNode();
final Node last = (Node)_nodeStk.peek();
ProcessingInstruction pi = _document.createProcessingInstruction(
target, data);
if (pi != null){
if (last == _root && _nextSibling != null)
last.insertBefore(pi, _nextSibling);
else
last.appendChild(pi);
_lastSibling = pi;
}
}
@Test public void compareProcessingInstructions() {
DOMDifferenceEngine d = new DOMDifferenceEngine();
DiffExpecter ex = new DiffExpecter(ComparisonType.PROCESSING_INSTRUCTION_TARGET);
d.addDifferenceListener(ex);
d.setComparisonController(ComparisonControllers.StopWhenDifferent);
ProcessingInstruction foo1 = doc.createProcessingInstruction("foo", "1");
ProcessingInstruction bar1 = doc.createProcessingInstruction("bar", "1");
assertEquals(wrap(ComparisonResult.EQUAL),
d.compareNodes(foo1, new XPathContext(),
foo1, new XPathContext()));
assertEquals(wrapAndStop(ComparisonResult.DIFFERENT),
d.compareNodes(foo1, new XPathContext(),
bar1, new XPathContext()));
assertEquals(1, ex.invoked);
d = new DOMDifferenceEngine();
ex = new DiffExpecter(ComparisonType.PROCESSING_INSTRUCTION_DATA);
d.addDifferenceListener(ex);
d.setComparisonController(ComparisonControllers.StopWhenDifferent);
ProcessingInstruction foo2 = doc.createProcessingInstruction("foo", "2");
assertEquals(wrap(ComparisonResult.EQUAL),
d.compareNodes(foo1, new XPathContext(),
foo1, new XPathContext()));
assertEquals(wrapAndStop(ComparisonResult.DIFFERENT),
d.compareNodes(foo1, new XPathContext(),
foo2, new XPathContext()));
assertEquals(1, ex.invoked);
}
public void print(Node node) throws XMLStreamException {
switch (node.getNodeType()) {
case Node.DOCUMENT_NODE:
visitDocument((Document) node);
break;
case Node.DOCUMENT_FRAGMENT_NODE:
visitDocumentFragment((DocumentFragment) node);
break;
case Node.ELEMENT_NODE:
visitElement((Element) node);
break;
case Node.TEXT_NODE:
visitText((Text) node);
break;
case Node.CDATA_SECTION_NODE:
visitCDATASection((CDATASection) node);
break;
case Node.PROCESSING_INSTRUCTION_NODE:
visitProcessingInstruction((ProcessingInstruction) node);
break;
case Node.ENTITY_REFERENCE_NODE:
visitReference((EntityReference) node);
break;
case Node.COMMENT_NODE:
visitComment((Comment) node);
break;
case Node.DOCUMENT_TYPE_NODE:
break;
case Node.ATTRIBUTE_NODE:
case Node.ENTITY_NODE:
default:
throw new XMLStreamException("Unexpected DOM Node Type "
+ node.getNodeType()
);
}
}
@Test
public void testPINode() {
try {
Document xmlDocument = createNewDocument();
ProcessingInstruction piNode = xmlDocument.createProcessingInstruction("execute", "test");
String outerXML = getOuterXML(piNode);
System.out.println("OuterXML of Comment Node is:" + outerXML);
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Exception occured: " + e.getMessage());
}
}
@Test
public void test() throws Exception {
Document document = createDOMWithNS("PITest01.xml");
ProcessingInstruction pi = document.createProcessingInstruction("PI", "processing");
assertEquals(pi.getData(), "processing");
assertEquals(pi.getTarget(), "PI");
pi.setData("newProcessing");
assertEquals(pi.getData(), "newProcessing");
}
final void setLocalName(String localName) {
if (dom instanceof ProcessingInstruction) {
setProcessingInstructionName(localName);
} else {
String prefix = dom.getPrefix();
if (prefix == null) prefix = "";
this.dom = dom.getOwnerDocument().renameNode(dom, dom.getNamespaceURI(), QName.qualify(prefix, localName));
}
}
public void print(Node node) throws XMLStreamException {
switch (node.getNodeType()) {
case Node.DOCUMENT_NODE:
visitDocument((Document) node);
break;
case Node.DOCUMENT_FRAGMENT_NODE:
visitDocumentFragment((DocumentFragment) node);
break;
case Node.ELEMENT_NODE:
visitElement((Element) node);
break;
case Node.TEXT_NODE:
visitText((Text) node);
break;
case Node.CDATA_SECTION_NODE:
visitCDATASection((CDATASection) node);
break;
case Node.PROCESSING_INSTRUCTION_NODE:
visitProcessingInstruction((ProcessingInstruction) node);
break;
case Node.ENTITY_REFERENCE_NODE:
visitReference((EntityReference) node);
break;
case Node.COMMENT_NODE:
visitComment((Comment) node);
break;
case Node.DOCUMENT_TYPE_NODE:
break;
case Node.ATTRIBUTE_NODE:
case Node.ENTITY_NODE:
default:
throw new XMLStreamException("Unexpected DOM Node Type "
+ node.getNodeType()
);
}
}
public void print(Node node) throws XMLStreamException {
switch (node.getNodeType()) {
case Node.DOCUMENT_NODE:
visitDocument((Document) node);
break;
case Node.DOCUMENT_FRAGMENT_NODE:
visitDocumentFragment((DocumentFragment) node);
break;
case Node.ELEMENT_NODE:
visitElement((Element) node);
break;
case Node.TEXT_NODE:
visitText((Text) node);
break;
case Node.CDATA_SECTION_NODE:
visitCDATASection((CDATASection) node);
break;
case Node.PROCESSING_INSTRUCTION_NODE:
visitProcessingInstruction((ProcessingInstruction) node);
break;
case Node.ENTITY_REFERENCE_NODE:
visitReference((EntityReference) node);
break;
case Node.COMMENT_NODE:
visitComment((Comment) node);
break;
case Node.DOCUMENT_TYPE_NODE:
break;
case Node.ATTRIBUTE_NODE:
case Node.ENTITY_NODE:
default:
throw new XMLStreamException("Unexpected DOM Node Type "
+ node.getNodeType()
);
}
}
/**
* adds processing instruction node to DOM.
*/
public void processingInstruction(String target, String data) {
appendTextNode();
final Node last = (Node)_nodeStk.peek();
ProcessingInstruction pi = _document.createProcessingInstruction(
target, data);
if (pi != null){
if (last == _root && _nextSibling != null)
last.insertBefore(pi, _nextSibling);
else
last.appendChild(pi);
_lastSibling = pi;
}
}
/**
* is not supported in this release.
* @param target {@inheritDoc}
* @throws javax.xml.stream.XMLStreamException {@inheritDoc}
*/
public void writeProcessingInstruction(String target) throws XMLStreamException {
if(target == null){
throw new XMLStreamException("Target cannot be null");
}
ProcessingInstruction pi = ownerDoc.createProcessingInstruction(target, "");
currentNode.appendChild(pi);
}
@Test
public void testGetWadlFromWadlLocation() throws Exception {
String address = "http://localhost:" + PORT + "/the/generated";
WebClient client = WebClient.create(address + "/bookstore" + "?_wadl&_type=xml");
Document doc = StaxUtils.read(new InputStreamReader(client.get(InputStream.class), StandardCharsets.UTF_8));
List<Element> resources = checkWadlResourcesInfo(doc, address, "/schemas/book.xsd", 2);
assertEquals("", resources.get(0).getAttribute("type"));
String type = resources.get(1).getAttribute("type");
String resourceTypeAddress = address + "/bookstoreImportResourceType.wadl#bookstoreType";
assertEquals(resourceTypeAddress, type);
checkSchemas(address, "/schemas/book.xsd", "/schemas/chapter.xsd", "include");
checkSchemas(address, "/schemas/chapter.xsd", null, null);
// check resource type resource
checkWadlResourcesType(address, resourceTypeAddress, "/schemas/book.xsd");
String templateRef = null;
NodeList nd = doc.getChildNodes();
for (int i = 0; i < nd.getLength(); i++) {
Node n = nd.item(i);
if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
String piData = ((ProcessingInstruction)n).getData();
int hRefStart = piData.indexOf("href=\"");
if (hRefStart > 0) {
int hRefEnd = piData.indexOf("\"", hRefStart + 6);
templateRef = piData.substring(hRefStart + 6, hRefEnd);
}
}
}
assertNotNull(templateRef);
WebClient client2 = WebClient.create(templateRef);
WebClient.getConfig(client2).getHttpConduit().getClient().setReceiveTimeout(1000000L);
String template = client2.get(String.class);
assertNotNull(template);
assertTrue(template.indexOf("<xsl:stylesheet") != -1);
}
final void setLocalName(String localName) {
if (dom instanceof ProcessingInstruction) {
setProcessingInstructionName(localName);
} else {
String prefix = dom.getPrefix();
if (prefix == null) prefix = "";
this.dom = dom.getOwnerDocument().renameNode(dom, dom.getNamespaceURI(), QName.qualify(prefix, localName));
}
}
static Filter PROCESSING_INSTRUCTION(final XMLName name) {
return new Filter() {
@Override
boolean accept(Node node) {
if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
ProcessingInstruction pi = (ProcessingInstruction)node;
return name.matchesLocalName(pi.getTarget());
}
return false;
}
};
}
public final void testProcessingInstructions() {
Document doc = DomParser.makeDocument(null, null);
ProcessingInstruction pi = doc.createProcessingInstruction("foo", "bar");
assertEquals("<?foo bar?>", Nodes.render(pi, MarkupRenderMode.XML));
}
private void handleWsDoesntAlterOriginal(Map.Entry<Document, Node> s) {
NodeList top = s.getKey().getChildNodes();
assertEquals(1, top.getLength());
assertTrue(top.item(0) instanceof Element);
assertEquals("root", top.item(0).getNodeName());
NodeList rootsChildren = top.item(0).getChildNodes();
assertEquals(10, rootsChildren.getLength());
assertNewlineTextNode(rootsChildren.item(0));
assertTrue("should be comment, is " + rootsChildren.item(1).getClass(),
rootsChildren.item(1) instanceof Comment);
assertEquals(" trim\tme ", ((Comment) rootsChildren.item(1)).getData());
assertNewlineTextNode(rootsChildren.item(2));
assertTrue("should be element, is " + rootsChildren.item(3).getClass(),
rootsChildren.item(3) instanceof Element);
assertEquals("child", rootsChildren.item(3).getNodeName());
assertTrue("should be cdata, is " + rootsChildren.item(4).getClass(),
rootsChildren.item(4) instanceof CDATASection);
assertEquals(" trim me ",
((CDATASection) rootsChildren.item(4)).getData());
assertNewlineTextNode(rootsChildren.item(5));
assertTrue("should be PI, is " + rootsChildren.item(6).getClass(),
rootsChildren.item(6) instanceof ProcessingInstruction);
assertEquals("trim me ",
((ProcessingInstruction) rootsChildren.item(6)).getData());
assertNewlineTextNode(rootsChildren.item(7));
assertTrue("should be cdata, is " + rootsChildren.item(8).getClass(),
rootsChildren.item(8) instanceof CDATASection);
assertEquals(" ",
((CDATASection) rootsChildren.item(8)).getData());
assertNewlineTextNode(rootsChildren.item(9));
Node child = rootsChildren.item(3);
NodeList grandChildren = child.getChildNodes();
assertEquals(1, grandChildren.getLength());
assertTrue("should be text, is " + grandChildren.item(0).getClass(),
grandChildren.item(0) instanceof Text);
assertEquals("\n trim me \n", ((Text) grandChildren.item(0)).getData());
NamedNodeMap attrs = child.getAttributes();
assertEquals(2, attrs.getLength());
Attr a = (Attr) attrs.getNamedItem("attr");
assertEquals(" trim me ", a.getValue());
Attr a2 = (Attr) attrs.getNamedItem("attr2");
assertEquals("not me", a2.getValue());
}
@Override
protected void outputPItoWriter(ProcessingInstruction currentPI,
OutputStream writer, int position) throws IOException {
// Processing Instructions before or after the document element are not treated specially
super.outputPItoWriter(currentPI, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT);
}