本文整理匯總了Java中javax.xml.parsers.DocumentBuilderFactory.setValidating方法的典型用法代碼示例。如果您正苦於以下問題:Java DocumentBuilderFactory.setValidating方法的具體用法?Java DocumentBuilderFactory.setValidating怎麽用?Java DocumentBuilderFactory.setValidating使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類javax.xml.parsers.DocumentBuilderFactory
的用法示例。
在下文中一共展示了DocumentBuilderFactory.setValidating方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: parse
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
public Document parse()
{
Document doc = null;
try
{
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
doc = factory.newDocumentBuilder().parse(_file);
parseDocument(doc);
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Error loading file " + _file, e);
}
return doc;
}
示例2: testGetOwnerItemList
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
/**
* Check grammar caching with imported schemas.
*
* @throws Exception If any errors occur.
* @see <a href="content/coins.xsd">coins.xsd</a>
* @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a>
*/
@Test
public void testGetOwnerItemList() throws Exception {
String xsdFile = XML_DIR + "coins.xsd";
String xmlFile = XML_DIR + "coins.xml";
try(FileInputStream fis = new FileInputStream(xmlFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
dbf.setValidating(false);
SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File(((xsdFile))));
MyErrorHandler eh = new MyErrorHandler();
Validator validator = schema.newValidator();
validator.setErrorHandler(eh);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document document = docBuilder.parse(fis);
validator.validate(new DOMSource(document), new DOMResult());
assertFalse(eh.isAnyError());
}
}
示例3: getDocument
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
/**
* Parse the input source and return a Document.
* @param source The {@code InputSource} of the document
* @return a DOM Document
* @throws XPathExpressionException if there is an error parsing the source.
*/
Document getDocument(InputSource source)
throws XPathExpressionException {
requireNonNull(source, "Source");
try {
// we'd really like to cache those DocumentBuilders, but we can't because:
// 1. thread safety. parsers are not thread-safe, so at least
// we need one instance per a thread.
// 2. parsers are non-reentrant, so now we are looking at having a
// pool of parsers.
// 3. then the class loading issue. The look-up procedure of
// DocumentBuilderFactory.newInstance() depends on context class loader
// and system properties, which may change during the execution of JVM.
//
// so we really have to create a fresh DocumentBuilder every time we need one
// - KK
DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(useServiceMechanism);
dbf.setNamespaceAware(true);
dbf.setValidating(false);
return dbf.newDocumentBuilder().parse(source);
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new XPathExpressionException (e);
}
}
示例4: test1
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
@Test
public void test1() throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute(SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
dbf.setAttribute(SCHEMA_SOURCE, Bug4966138.class.getResource("test.xsd").toExternalForm());
Document document = dbf.newDocumentBuilder().parse(Bug4966138.class.getResource("test.xml").toExternalForm());
TypeInfo type = document.getDocumentElement().getSchemaTypeInfo();
String typeName = type.getTypeName();
System.out.println(typeName);
Assert.assertNotNull(typeName);
Assert.assertTrue(typeName.length() != 0, "returned typeName shouldn't be empty");
String typeNs = type.getTypeNamespace();
System.out.println(typeNs);
Assert.assertNotNull(typeNs);
Assert.assertTrue(typeNs.length() != 0, "returned typeNamespace shouldn't be empty");
}
示例5: parse
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
public static Flag parse(String name, InputStream in) throws IOException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true); // make sure the XML is valid
factory.setExpandEntityReferences(false); // don't allow custom entities
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new KVXXEntityResolver());
builder.setErrorHandler(new KVXXErrorHandler(name));
Document document = builder.parse(new InputSource(in));
return parseDocument(document);
} catch (ParserConfigurationException pce) {
throw new IOException(pce);
} catch (SAXException saxe) {
throw new IOException(saxe);
}
}
示例6: loadXML
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
public void loadXML() throws SAXException, IOException, ParserConfigurationException
{
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
final File file = new File(Config.DATAPACK_ROOT + "/data/" + MPCS_FILE);
if (file.exists())
{
int defaultPriceConfigId;
final Document doc = factory.newDocumentBuilder().parse(file);
Node n = doc.getDocumentElement();
final Node dpcNode = n.getAttributes().getNamedItem("defaultPriceConfig");
if (dpcNode == null)
{
throw new IllegalStateException("merchantPriceConfig must define an 'defaultPriceConfig'");
}
defaultPriceConfigId = Integer.parseInt(dpcNode.getNodeValue());
MerchantPriceConfig mpc;
for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{
mpc = parseMerchantPriceConfig(n);
if (mpc != null)
{
_mpcs.put(mpc.getId(), mpc);
}
}
final MerchantPriceConfig defaultMpc = this.getMerchantPriceConfig(defaultPriceConfigId);
if (defaultMpc == null)
{
throw new IllegalStateException("'defaultPriceConfig' points to an non-loaded priceConfig");
}
_defaultMpc = defaultMpc;
}
}
示例7: getW3CXmlDoc
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
/**
* Gets a org.w3c.dom.Document for this record. This method is optimized to create only one DOM when
* accessed multiple times for the same XMLDocReader.
*
* @return A org.w3c.dom.Document, or null if unable to read.
*/
public org.w3c.dom.Document getW3CXmlDoc() {
if (w3cXmlDoc != null)
return w3cXmlDoc;
DocumentBuilderFactory docfactory
= DocumentBuilderFactory.newInstance();
docfactory.setCoalescing(true);
docfactory.setExpandEntityReferences(true);
docfactory.setIgnoringComments(true);
docfactory.setNamespaceAware(true);
// We must set validation false since jdk1.4 parser
// doesn't know about schemas.
docfactory.setValidating(false);
// Ignore whitespace doesn't work unless setValidating(true),
// according to javadocs.
docfactory.setIgnoringElementContentWhitespace(false);
try {
DocumentBuilder docbuilder = docfactory.newDocumentBuilder();
w3cXmlDoc = docbuilder.parse(getXml());
} catch (Throwable e) {
return null;
}
return w3cXmlDoc;
}
示例8: loadXmlResource
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
/**
* Load XML resource.
*
* @param pResource the resource
* @return the document
* @throws Exception in case a problem occurred
*/
public static Document loadXmlResource(String pResource) throws Exception {
String tResource = (pResource.startsWith("/") ? pResource.substring(1) : pResource);
InputStream tStream = null;
/**
* Try own class loader first, then the system class loader
*/
tStream = AsXmlTool.class.getClassLoader().getResourceAsStream(tResource);
if (tStream == null) {
tStream = ClassLoader.getSystemResourceAsStream(tResource);
}
if (tStream == null) {
tStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(tResource);
}
if (tStream == null) {
throw new RuntimeException("Failed to locate module '" + pResource + "'");
}
DocumentBuilderFactory tFactory = DocumentBuilderFactory.newInstance();
tFactory.setIgnoringComments(true);
tFactory.setNamespaceAware(false); // No namespaces: this is default
tFactory.setValidating(false); // Don't validate DTD: also default
DocumentBuilder tParser = tFactory.newDocumentBuilder();
return tParser.parse(tStream);
}
示例9: createDocumentBuilderFactory
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
/**
* Create the {@link DocumentBuilderFactory} instance.
* @param validationMode the type of validation: {@link XmlValidationModeDetector#VALIDATION_DTD DTD}
* or {@link XmlValidationModeDetector#VALIDATION_XSD XSD})
* @param namespaceAware whether the returned factory is to provide support for XML namespaces
* @return the JAXP DocumentBuilderFactory
* @throws ParserConfigurationException if we failed to build a proper DocumentBuilderFactory
*/
protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {
factory.setValidating(true);
if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {
// Enforce namespace aware for XSD...
factory.setNamespaceAware(true);
try {
factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
}
catch (IllegalArgumentException ex) {
ParserConfigurationException pcex = new ParserConfigurationException(
"Unable to validate using XSD: Your JAXP provider [" + factory +
"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +
"Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
pcex.initCause(ex);
throw pcex;
}
}
}
return factory;
}
示例10: SAX2DOMEx
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
/**
* Creates a fresh empty DOM document and adds nodes under this document.
* @deprecated
*/
public SAX2DOMEx() throws ParserConfigurationException {
DocumentBuilderFactory factory = XmlFactory.createDocumentBuilderFactory(false);
factory.setValidating(false);
document = factory.newDocumentBuilder().newDocument();
node = document;
nodeStack.push(document);
}
示例11: toXmlDocument
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
private Document toXmlDocument(String xmlString) throws Exception {
InputSource xmlInputSource = new InputSource(new StringReader(xmlString));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
DocumentBuilder xmlDocumentBuilder = dbf.newDocumentBuilder();
Document node = xmlDocumentBuilder.parse(xmlInputSource);
return node;
}
示例12: load
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
public void load(){
try {
phrases.clear();
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setValidating(false);
DocumentBuilder builder = f.newDocumentBuilder();
InputStream inputStream = Files.newInputStream(packFile);
Document doc = builder.parse(inputStream);
inputStream.close();
Node mainNode = doc.getChildNodes().item(0);
NodeList list = mainNode.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
if (!list.item(i).getNodeName().equals("phrase")) continue;
try {
add(Phrase.create(list.item(i)));
} catch (Exception e2) {
Main.log(e2);
}
}
} catch (Exception e) {
Main.log("Error while parsing phrases file " + packName + ": " + e.getMessage());
loaded = false;
return;
}
loaded = true;
}
示例13: loadDiagram
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
/**
* Load a SVG document into a diagram
*
* @param in
* The input stream from which to read the SVG
* @param offset
* Offset the diagram for the height of the document
* @return The diagram loaded
* @throws SlickException
* Indicates a failure to process the document
*/
private Diagram loadDiagram(InputStream in, boolean offset)
throws SlickException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId,
String systemId) throws SAXException, IOException {
return new InputSource(
new ByteArrayInputStream(new byte[0]));
}
});
Document doc = builder.parse(in);
Element root = doc.getDocumentElement();
String widthString = root.getAttribute("width");
while (Character.isLetter(widthString
.charAt(widthString.length() - 1))) {
widthString = widthString.substring(0, widthString.length() - 1);
}
String heightString = root.getAttribute("height");
while (Character.isLetter(heightString
.charAt(heightString.length() - 1))) {
heightString = heightString.substring(0,heightString.length() - 1);
}
float docWidth = Float.parseFloat(widthString);
float docHeight = Float.parseFloat(heightString);
diagram = new Diagram(docWidth, docHeight);
if (!offset) {
docHeight = 0;
}
loadChildren(root, Transform
.createTranslateTransform(0, -docHeight));
return diagram;
} catch (Exception e) {
throw new SlickException("Failed to load inkscape document", e);
}
}
示例14: testGenerateArchFileWhenEmptyWithDefaultAnswerForNbDepsQuestion
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
public void testGenerateArchFileWhenEmptyWithDefaultAnswerForNbDepsQuestion() throws Exception {
java.io.File answers = extractString ("");
answers.delete ();
assertFalse ("Really deleted", answers.exists ());
java.io.File f = extractString (
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<project name=\"Test Arch\" basedir=\".\" default=\"all\" >" +
" <taskdef name=\"arch\" classname=\"org.netbeans.nbbuild.Arch\" classpath=\"${nbantext.jar}\"/>" +
" <arch answers=\"" + answers + "\" output=\"x.html\" />" +
"<target name=\"all\" >" +
" " +
"</target>" +
"</project>"
);
execute (f, new String[] { });
assertTrue ("File is generated", answers.exists ());
String res = readFile(answers);
DocumentBuilderFactory fack = DocumentBuilderFactory.newInstance();
fack.setValidating(false);
DocumentBuilder build = fack.newDocumentBuilder();
build.setEntityResolver(this);
org.w3c.dom.Document dom;
try {
dom = build.parse(answers);
} catch (IOException ex) {
throw new IOException(ex.getMessage() + "\n" + msg.toString(), ex);
}
org.w3c.dom.NodeList list = dom.getElementsByTagName("defaultanswer");
assertTrue("There is at least one defaultanswer: " + res, list.getLength() > 0);
BIGLOOP: for (int i = 0; i < list.getLength(); i++) {
org.w3c.dom.Node n = list.item(i);
while (n != null) {
n = n.getParentNode();
assertNotNull ("No parent node answer found: " + res, n);
if (n.getNodeName().equals ("answer")) {
String id = n.getAttributes().getNamedItem("id").getNodeValue();
if (id.equals ("dep-nb")) {
// ok, we were searching for answer to dep-nb question
return;
}
continue BIGLOOP;
}
}
}
fail ("dep-nb question should have a defaultanswer: " + res);
}
示例15: testAddUser
import javax.xml.parsers.DocumentBuilderFactory; //導入方法依賴的package包/類
/**
* Checking conflicting namespaces and use renameNode and normalizeDocument.
* @see <a href="content/accountInfo.xml">accountInfo.xml</a>
*
* @throws Exception If any errors occur.
*/
@Test
public void testAddUser() throws Exception {
String resultFile = USER_DIR + "accountRole.out";
String xmlFile = XML_DIR + "accountInfo.xml";
// Copy schema for outputfile
Files.copy(Paths.get(XML_DIR, "accountInfo.xsd"),
Paths.get(USER_DIR, "accountInfo.xsd"),
StandardCopyOption.REPLACE_EXISTING);
MyErrorHandler eh = new MyErrorHandler();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
dbf.setNamespaceAware(true);
dbf.setValidating(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
docBuilder.setErrorHandler(eh);
Document document = docBuilder.parse(xmlFile);
Element sell = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Sell").item(0);
Element role = (Element) sell.getParentNode();
Element buy = (Element) document.renameNode(sell, PORTAL_ACCOUNT_NS, "acc:Buy");
role.appendChild(buy);
DOMImplementationLS impl
= (DOMImplementationLS) DOMImplementationRegistry
.newInstance().getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
try(FileOutputStream output = new FileOutputStream(resultFile)) {
MyDOMOutput mydomoutput = new MyDOMOutput();
mydomoutput.setByteStream(output);
writer.write(document, mydomoutput);
}
docBuilder.parse(resultFile);
assertFalse(eh.isAnyError());
}