本文整理了Java中org.w3c.dom.Document
类的一些代码示例,展示了Document
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Document
类的具体详情如下:
包路径:org.w3c.dom.Document
类名称:Document
[英]The Document
interface represents the entire HTML or XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data.
Since elements, text nodes, comments, processing instructions, etc. cannot exist outside the context of a Document
, the Document
interface also contains the factory methods needed to create these objects. The Node
objects created have a ownerDocument
attribute which associates them with the Document
within whose context they were created.
See also the Document Object Model (DOM) Level 3 Core Specification.
[中]Document
接口表示整个HTML或XML文档。从概念上讲,它是文档树的根,并提供对文档数据的主要访问。
由于元素、文本节点、注释、处理指令等不能存在于Document
的上下文之外,因此Document
接口还包含创建这些对象所需的工厂方法。所创建的Node
对象具有ownerDocument
属性,该属性将它们与在其上下文中创建它们的Document
相关联。
另见Document Object Model (DOM) Level 3 Core Specification。
代码示例来源:origin: stanfordnlp/CoreNLP
public static Element parseElement(String xml) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes()));
return doc.getDocumentElement();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
代码示例来源:origin: stackoverflow.com
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new File("XmlTest.xml"));
NodeList nodes = doc.getElementsByTagName("CustomerId");
Text a = doc.createTextNode("value");
Element p = doc.createElement("newNode");
p.appendChild(a);
nodes.item(0).getParentNode().insertBefore(p, nodes.item(0));
代码示例来源:origin: pmd/pmd
private Document initDocument() throws IOException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder;
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new IOException("Failed to create settings document builder", e);
}
Document document = documentBuilder.newDocument();
Element settingsElement = document.createElement(SCHEMA_DOCUMENT_ELEMENT);
settingsElement.setAttribute(SCHEMA_MODEL_VERSION, "" + getRevisionNumber());
document.appendChild(settingsElement);
return document;
}
代码示例来源:origin: pmd/pmd
private Element createTextElement(String name, String value) {
Element element = document.createElementNS(RULESET_2_0_0_NS_URI, name);
Text text = document.createTextNode(value);
element.appendChild(text);
return element;
}
代码示例来源:origin: pmd/pmd
private Element createCDATASectionElement(String name, String value) {
Element element = document.createElementNS(RULESET_2_0_0_NS_URI, name);
CDATASection cdataSection = document.createCDATASection(value);
element.appendChild(cdataSection);
return element;
}
}
代码示例来源:origin: apache/hive
private Element appendElement(Element parent, String name, String text) {
Document document = parent.getOwnerDocument();
Element child = document.createElement(name);
parent.appendChild(child);
if (text != null) {
Text textNode = document.createTextNode(text);
child.appendChild(textNode);
}
return child;
}
代码示例来源:origin: marytts/marytts
public KlattDurationParams(String filename) throws SAXException, IOException, ParserConfigurationException {
// parse the xml file:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(filename));
// In document, ignore everything that is not a segment element:
NodeList segElements = document.getElementsByTagName("segment");
for (int i = 0; i < segElements.getLength(); i++) {
Element seg = (Element) segElements.item(i);
String name = seg.getAttribute("s");
int inherentDuration = Integer.parseInt(seg.getAttribute("inh"));
int minimalDuration = Integer.parseInt(seg.getAttribute("min"));
inh.put(name, inherentDuration);
min.put(name, minimalDuration);
}
}
代码示例来源:origin: wildfly/wildfly
protected void parseRules(InputStream input) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false); // for now
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(input);
Element root=document.getDocumentElement();
match(RULES, root.getNodeName(), true);
NodeList children=root.getChildNodes();
if(children == null || children.getLength() == 0)
return;
for(int i=0; i < children.getLength(); i++) {
Node node=children.item(i);
if(node.getNodeType() != Node.ELEMENT_NODE)
continue;
String element_name=node.getNodeName();
if(RULE.equals(element_name))
parseRule(node);
else
throw new Exception("expected <" + RULE + ">, but got " + "<" + element_name + ">");
}
}
代码示例来源:origin: androidannotations/androidannotations
private AndroidManifest parse(File androidManifestFile, boolean libraryProject) throws AndroidManifestNotFoundException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse(androidManifestFile);
} catch (Exception e) {
LOGGER.error("Could not parse the AndroidManifest.xml file at path {}", androidManifestFile, e);
Element documentElement = doc.getDocumentElement();
documentElement.normalize();
String applicationPackage = documentElement.getAttribute("package");
boolean applicationDebuggableMode = false;
if (applicationNodes.getLength() > 0) {
Node applicationNode = applicationNodes.item(0);
Node nameAttribute = applicationNode.getAttributes().getNamedItem("android:name");
LOGGER.warn("The class application declared in the AndroidManifest.xml cannot be found in the compile path: [{}]", nameAttribute.getNodeValue());
Node debuggableAttribute = applicationNode.getAttributes().getNamedItem("android:debuggable");
if (debuggableAttribute != null) {
applicationDebuggableMode = debuggableAttribute.getNodeValue().equalsIgnoreCase("true");
代码示例来源:origin: alipay/sofa-boot
private static String getDependencyManagementPluginVersion() {
try (FileReader pomReader = new FileReader("pom.xml")) {
Document pom = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(pomReader));
NodeList dependencyElements = pom.getElementsByTagName("dependency");
for (int i = 0; i < dependencyElements.getLength(); i++) {
Element dependency = (Element) dependencyElements.item(i);
if (dependency.getElementsByTagName("artifactId").item(0).getTextContent()
.equals("dependency-management-plugin")) {
return dependency.getElementsByTagName("version").item(0).getTextContent();
}
}
throw new IllegalStateException("dependency management plugin version not found");
} catch (Exception ex) {
throw new IllegalStateException("Failed to find dependency management plugin version",
ex);
}
}
代码示例来源:origin: libgdx/libgdx
private void initData () throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbFactory.newDocumentBuilder();
Document doc = builder.parse(ExternalExtensionsDialog.class
.getResourceAsStream("/com/badlogic/gdx/setup/data/extensions.xml"));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("extension");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
String name = eElement.getElementsByTagName("name").item(0).getTextContent();
String description = eElement.getElementsByTagName("description").item(0).getTextContent();
String version = eElement.getElementsByTagName("version").item(0).getTextContent();
String compatibility = eElement.getElementsByTagName("compatibility").item(0).getTextContent();
代码示例来源:origin: stackoverflow.com
public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException, TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("document.xml"));
doSomething(document.getDocumentElement());
}
public static void doSomething(Node node) {
// do something with the current node instead of System.out
System.out.println(node.getNodeName());
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
//calls this method for all the children which is Element
doSomething(currentNode);
}
}
}
代码示例来源:origin: languagetool-org/languagetool
private static Source mergeIntoSource(InputStream baseXmlStream, InputStream xmlStream) throws Exception {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setIgnoringComments(true);
domFactory.setValidating(false);
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document baseDoc = builder.parse(baseXmlStream);
Document ruleDoc = builder.parse(xmlStream);
// Shall this be more generic, i.e. reuse not just unification ???
NodeList unificationNodes = baseDoc.getElementsByTagName("unification");
Node ruleNode = ruleDoc.getElementsByTagName("rules").item(0);
Node firstChildRuleNode = ruleNode.getChildNodes().item(1);
for (int i = 0; i < unificationNodes.getLength(); i++) {
Node unificationNode = ruleDoc.importNode(unificationNodes.item(i), true);
ruleNode.insertBefore(unificationNode, firstChildRuleNode);
}
return new DOMSource(ruleDoc);
}
代码示例来源:origin: stackoverflow.com
public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException, TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("document.xml"));
NodeList nodeList = document.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
// do something with the current element
System.out.println(node.getNodeName());
}
}
}
代码示例来源:origin: Tencent/tinker
private void parse() throws ParserException {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
Document document;
try {
DocumentBuilder builder = builderFactory.newDocumentBuilder();
builder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
document = builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
Node manifestNode = document.getElementsByTagName("manifest").item(0);
NodeList nodes = manifestNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
String nodeName = node.getNodeName();
if (nodeName.equals("application")) {
NodeList children = node.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node child = children.item(j);
代码示例来源:origin: stackoverflow.com
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("input.xml"));
NodeList nodeList = document.getElementsByTagName("Item");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue());
}
}
}
代码示例来源:origin: stanfordnlp/CoreNLP
/**
* Returns the text content of all nodes in the given file with the given tag.
* If the text contents contains embedded tags, strips the embedded tags out
* of the returned text. E.g., {@code <s>This is a <s>sentence</s> with embedded tags
* </s>} would return the list containing ["This is a sentence with embedded
* tags", "sentence"].
*
* @throws SAXException if tag doesn't exist in the file.
* @return List of String text contents of tags.
*/
private static List<Element> getTagElementsFromFileSAXException(
File f, String tag) throws SAXException {
List<Element> sents = Generics.newArrayList();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
doc.getDocumentElement().normalize();
NodeList nodeList=doc.getElementsByTagName(tag);
for (int i = 0; i < nodeList.getLength(); i++) {
// Get element
Element element = (Element)nodeList.item(i);
sents.add(element);
}
} catch (IOException | ParserConfigurationException e) {
log.warn(e);
}
return sents;
}
代码示例来源:origin: stackoverflow.com
//obtain Document somehow, doesn't matter how
DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
org.w3c.dom.Document doc = b.parse(new FileInputStream("page.html"));
//Evaluate XPath against Document itself
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xPath.evaluate("/html/body/p/div[3]/a",
doc.getDocumentElement(), XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
Element e = (Element) nodes.item(i);
}
代码示例来源:origin: wildfly/wildfly
protected static List<Triple<Short,String,Boolean>> parse(InputStream stream) throws Exception {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
factory.setValidating(false); // for now
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(stream);
NodeList class_list=document.getElementsByTagName("class");
List<Triple<Short,String,Boolean>> list=new LinkedList<>();
for(int i=0; i < class_list.getLength(); i++) {
if(class_list.item(i).getNodeType() == Node.ELEMENT_NODE) {
list.add(parseClassData(class_list.item(i)));
}
}
return list;
}
代码示例来源:origin: robolectric/robolectric
private static String getTagAttributeText(final Document doc, final String tag, final String attribute) {
NodeList elementsByTagName = doc.getElementsByTagName(tag);
for (int i = 0; i < elementsByTagName.getLength(); ++i) {
Node item = elementsByTagName.item(i);
Node namedItem = item.getAttributes().getNamedItem(attribute);
if (namedItem != null) {
return namedItem.getTextContent();
}
}
return null;
}
内容来源于网络,如有侵权,请联系作者删除!