本文整理汇总了Java中javax.xml.parsers.DocumentBuilder.parse方法的典型用法代码示例。如果您正苦于以下问题:Java DocumentBuilder.parse方法的具体用法?Java DocumentBuilder.parse怎么用?Java DocumentBuilder.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.xml.parsers.DocumentBuilder
的用法示例。
在下文中一共展示了DocumentBuilder.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: unmarshal
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
*Converts xml-stream into its equivalent jaxb object
*
* @param xmlInputStream
* @param type
* @return
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws JAXBException
*/
public Object unmarshal(InputStream xmlInputStream, Class<?> type)
throws ParserConfigurationException, SAXException, IOException, JAXBException {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setExpandEntityReferences(false);
builderFactory.setNamespaceAware(true);
builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION, true);
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlInputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(type);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return jaxbUnmarshaller.unmarshal(document);
}
示例2: testNodes2XML
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
@Test
public void testNodes2XML() throws JSONException, Exception {
rm.start();
WebResource r = resource();
rm.registerNode("h1:1234", 5120);
rm.registerNode("h2:1235", 5121);
ClientResponse response = r.path("ws").path("v1").path("cluster")
.path("nodes").accept(MediaType.APPLICATION_XML)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String xml = response.getEntity(String.class);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList nodesApps = dom.getElementsByTagName("nodes");
assertEquals("incorrect number of elements", 1, nodesApps.getLength());
NodeList nodes = dom.getElementsByTagName("node");
assertEquals("incorrect number of elements", 2, nodes.getLength());
rm.stop();
}
示例3: testCheckElementContentWhitespace
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
* Test for the isIgnoringElementContentWhitespace and the
* setIgnoringElementContentWhitespace. The xml file has all kinds of
* whitespace,tab and newline characters, it uses the MyNSContentHandler
* which does not invoke the characters callback when this
* setIgnoringElementContentWhitespace is set to true.
* @throws Exception If any errors occur.
*/
@Test
public void testCheckElementContentWhitespace() throws Exception {
String goldFile = GOLDEN_DIR + "dbfactory02GF.out";
String outputFile = USER_DIR + "dbfactory02.out";
MyErrorHandler eh = MyErrorHandler.newInstance();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
assertFalse(dbf.isIgnoringElementContentWhitespace());
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(eh);
Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory06.xml"));
assertFalse(eh.isErrorOccured());
DOMSource domSource = new DOMSource(doc);
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer transformer = tfactory.newTransformer();
SAXResult saxResult = new SAXResult();
try(MyCHandler handler = MyCHandler.newInstance(new File(outputFile))) {
saxResult.setHandler(handler);
transformer.transform(domSource, saxResult);
}
assertTrue(compareWithGold(goldFile, outputFile));
}
示例4: validateData
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
private static Document validateData(Object data, DocumentBuilder builder) throws SAXException, IOException {
Document doc;
if(data instanceof String) {
String path = data.toString();
if (isValidURL(path)) {
doc = builder.parse(new URL(path).openStream());
} else if (exists(path)) {
doc = builder.parse(path);
} else {
throw new FileNotFoundException(path + " doesn't exist. ");
}
} else {
doc = builder.parse(new ByteArrayInputStream((byte[])data));
}
return doc;
}
示例5: getOWLSkeleton
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
private Node getOWLSkeleton(Document doc, DocumentBuilder builder) throws IOException, SAXException {
String skeleton = "<?xml version=\"1.0\"?>" +
"" +
"<rdf:RDF xmlns:abstract-pass-ont=\"http://www.imi.kit.edu/abstract-pass-ont#\" xmlns:standard-pass-ont=\"http://www.i2pm.net/standard-pass-ont#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" xmlns=\"" + ontologyUri + "\">" +
" <owl:Ontology rdf:about=\""+ontologyUri+"\">" +
" <owl:versionIRI rdf:resource=\""+ontologyUri+"\"></owl:versionIRI>" +
" <owl:imports rdf:resource=\"http://www.imi.kit.edu/abstract-pass-ont\"></owl:imports>" +
" <owl:imports rdf:resource=\"http://www.i2pm.net/standard-pass-ont\"></owl:imports>" +
" </owl:Ontology>" +
"</rdf:RDF>";
Document doc2 = builder.parse(new ByteArrayInputStream(skeleton.getBytes()));
Node node = doc.importNode(doc2.getDocumentElement(), true);
doc.appendChild(node);
return node;
}
示例6: testWProlog
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
@Test
public void testWProlog() throws Exception {
try {
ByteArrayInputStream bais = new ByteArrayInputStream("<?xml version=\"1.1\" encoding=\"UTF-8\"?><?xmltarget foo?><test></test>".getBytes());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder xmlParser = factory.newDocumentBuilder();
// DOMParser p = new DOMParser();
Document document = xmlParser.parse(new InputSource(bais));
String result = ((ProcessingInstruction) document.getFirstChild()).getData();
System.out.println(result);
if (!result.equalsIgnoreCase("foo")) {
Assert.fail("missing PI data");
}
} catch (Exception e) {
}
}
示例7: test1
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
@Test
public void test1() throws Exception {
String xsd = "<?xml version='1.0'?>\n" + "<schema xmlns='http://www.w3.org/2001/XMLSchema'\n" + " xmlns:test='jaxp13_test1'\n"
+ " targetNamespace='jaxp13_test1'\n" + " elementFormDefault='qualified'>\n" + " <element name='test'/>\n" + "</schema>\n";
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Node document = docBuilder.parse(new InputSource(new StringReader(xsd)));
Assert.assertNotNull(document);
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = schemaFactory.newSchema(new Source[] { new DOMSource(document) });
Assert.assertNotNull(schema, "Failed: newSchema returned null.");
}
示例8: getDocument
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
public static Document getDocument(InputSource xml, InputStream xsd)
throws ParserConfigurationException, SAXException, IOException {
Document doc = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
if (xsd != null) {
dbf.setNamespaceAware(true);
}
DocumentBuilder builder = dbf.newDocumentBuilder();
doc = builder.parse(xml);
if (xsd != null) {
validateXml(doc, xsd);
}
} finally {
closeStream(xml.getByteStream());
}
return doc;
}
示例9: parseText
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
@Test
public void parseText() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code>\n" +
"<return_msg><![CDATA[OK]]></return_msg>\n" +
"<appid><![CDATA[wxa2dfabf4a3c52551]]></appid>\n" +
"<mch_id><![CDATA[1346733401]]></mch_id>\n" +
"<nonce_str><![CDATA[8q3K40bL86nhv4Vp]]></nonce_str>\n" +
"<sign><![CDATA[124A01D6ADF83B0D4048398F5E848A97]]></sign>\n" +
"<result_code><![CDATA[SUCCESS]]></result_code>\n" +
"<prepay_id><![CDATA[wx20170413154005a6b42d4ccd0214498848]]></prepay_id>\n" +
"<trade_type><![CDATA[NATIVE]]></trade_type>\n" +
"<code_url><![CDATA[weixin://wxpay/bizpayurl?pr=h3ZzLPU]]></code_url>\n" +
"</xml>";
InputSource inputSource = new InputSource(new StringReader(data));
Document document = builder.parse(inputSource);
System.out.println(DocumentUtil.getText(document,"return_code"));
// Element root = document.getDocumentElement();
// System.out.println(root.getNodeName());
// NodeList nodeList = root.getChildNodes();
// for (int i = 0; i < nodeList.getLength(); i++) {
// Node item = nodeList.item(i);
// if (item instanceof Element) {
// System.out.println(item.getNodeName() + "=" + item.getTextContent());
// }
// }
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
示例10: getWfCloneDetails
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
* Private method to get the values given in warriorframework
* tag of warhorn config file
*
* @param build Build
* @param workspace Jenkins job workspace
* @param listener Task listener
* @return cloneDetails Details required to clone warriorframework
* @throws ParserConfigurationException ParserConfigurationException
* @throws SAXException SAXException
* @throws IOException IOException
*/
private String[] getWfCloneDetails(Run<?,?> build, FilePath workspace, TaskListener listener)
throws ParserConfigurationException, SAXException, IOException{
String absWarhornConfig = "";
String[] cloneDetails = new String[4];
if (configType.equals("configGit")){
absWarhornConfig = workspace.getRemote() + "/configRepo/" + gitConfigFile;
} else {
absWarhornConfig = workspace.getRemote() + "/warhorn_config.xml";
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File(absWarhornConfig));
NodeList wfNodeList = document.getElementsByTagName("warriorframework");
String url = "";
String branch = "";
if(wfNodeList.getLength() > 0){
Element element = (Element) wfNodeList.item(0);
url = element.getAttribute("url");
branch = element.getAttribute("label");
}
if (url.isEmpty()){
url = "https://github.com/warriorframework/warriorframework.git";
}
if (branch.isEmpty()){
branch = "origin/develop";
}
// Temp_fix: Using the username & password given for cloning warhorn config file.
// These will be empty/default if not provided for warhorn config file
cloneDetails[0] = this.gitConfigUname;
cloneDetails[1] = this.gitConfigPwd;
cloneDetails[2] = url;
cloneDetails[3] = branch;
return cloneDetails;
}
示例11: verifySchedulerFifoXML
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
public void verifySchedulerFifoXML(String xml) throws JSONException,
Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList nodesSched = dom.getElementsByTagName("scheduler");
assertEquals("incorrect number of elements", 1, nodesSched.getLength());
NodeList nodes = dom.getElementsByTagName("schedulerInfo");
assertEquals("incorrect number of elements", 1, nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
verifyClusterSchedulerFifoGeneric(
WebServicesTestUtils.getXmlAttrString(element, "xsi:type"),
WebServicesTestUtils.getXmlString(element, "qstate"),
WebServicesTestUtils.getXmlFloat(element, "capacity"),
WebServicesTestUtils.getXmlFloat(element, "usedCapacity"),
WebServicesTestUtils.getXmlInt(element, "minQueueMemoryCapacity"),
WebServicesTestUtils.getXmlInt(element, "maxQueueMemoryCapacity"),
WebServicesTestUtils.getXmlInt(element, "numNodes"),
WebServicesTestUtils.getXmlInt(element, "usedNodeCapacity"),
WebServicesTestUtils.getXmlInt(element, "availNodeCapacity"),
WebServicesTestUtils.getXmlInt(element, "totalNodeCapacity"),
WebServicesTestUtils.getXmlInt(element, "numContainers"));
}
}
示例12: unsafeManualConfig1
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
public static void unsafeManualConfig1() throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(getInputFile());
print(doc);
}
示例13: stringToXmlDocumentObj
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
*
* @param xmlString xml string
* @return xml Document object
* @throws XmlUtilitiesException
*/
public static Document stringToXmlDocumentObj( String xmlString ) throws XmlUtilitiesException {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
return db.parse(new ByteArrayInputStream(xmlString.getBytes()));
} catch (Exception e) {
throw new XmlUtilitiesException("Error transforming String to XML document", e);
}
}
示例14: checkSchema
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
public static void checkSchema(Path solrSchemaPath, SchemaResponse response) throws IOException, SchemaValidationException {
// read the local schema.xml
final Document local;
try (InputStream xml = Files.newInputStream(solrSchemaPath, StandardOpenOption.READ)) {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
final DocumentBuilder builder = factory.newDocumentBuilder();
local = builder.parse(xml);
} catch (ParserConfigurationException | SAXException e) {
log.error("Error checking schema.xml: {}", e.getMessage(), e);
throw new IOException(e);
}
final SchemaRepresentation remote = response.getSchemaRepresentation();
final Element schema = local.getDocumentElement();
// check the field-types
final NodeList fieldTypes = schema.getElementsByTagName("fieldType");
final Set<String> fieldTypeNames = remote.getFieldTypes().stream()
.map(FieldTypeDefinition::getAttributes)
.map(m -> m.get("name"))
.filter(Objects::nonNull)
.map(String::valueOf)
.collect(Collectors.toSet());
for (int i = 0; i < fieldTypes.getLength(); i++) {
final Node fieldType = fieldTypes.item(i);
final String fieldTypeName = fieldType.getAttributes().getNamedItem("name").getNodeValue();
if (! fieldTypeNames.contains(fieldTypeName)) {
throw new SchemaValidationException(String.format("Missing <fieldType name='%s' />", fieldTypeName));
}
}
// TODO: check local -> remote.
}
示例15: documentFrom
import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
* This method closes the given input stream upon completion.
*/
public static Document documentFrom(InputStream is)
throws SAXException, IOException, ParserConfigurationException {
is = new NamespaceRemovingInputStream(is);
// DocumentBuilderFactory is not thread safe
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// ensure that parser writes error/warning messages to the logger
// rather than stderr
builder.setErrorHandler(ERROR_HANDLER);
Document doc = builder.parse(is);
is.close();
return doc;
}