我们可以使用dom解析器在xml文件中按id搜索元素,例如:
<root>
<context id="one">
<entity>
<identifier>new one</identifier>
</entity>
</context>
<context id="two">
<entity>
<identifier>second one</identifier>
</entity>
</context>
</root>
我想要一个id =“one”的节点,我的代码
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));
Element ele = document.getElementById("one");
返回null,
还有其他方法吗?
答案 0 :(得分:3)
Note: Attributes with the name "ID" or "id" are not of type ID unless so defined.
问题是Document
不知道名为id
的属性是标识符,除非你告诉它。在致电DocumentBuilderFactory
之前,您需要在newDocumentBuilder
上设置架构。这样DocumentBuilder
就会知道元素类型。
在架构中,您需要在适当的位置使用以下内容:
<xs:attribute name="id" type="xs:ID"/>
答案 1 :(得分:3)
您可以使用JDK / JRE中的javax.xml.xpath
API通过XPath查找元素。
示例强>
import java.io.File;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
Element element = (Element) xpath.evaluate("//*[@id='one']", document, XPathConstants.NODE);
}
}
答案 2 :(得分:0)
您可以使用像Jsoup这样的第三方库来完成这项工作。
File input = new File("/tmp/input.xml");
Document doc = Jsoup.parse(input, "UTF-8", "test");
然后你可以使用这样的东西:
doc.select("context#id=one")
这会回答你的问题吗?
答案 3 :(得分:0)
尝试使用XML - Xpath表达式非常容易
File fXmlFile = new File("filePath");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
String expression;
Node node;
// 1. elements with id '1'
expression = "//context[@id='one']";
node = (Node ) xpath.evaluate(expression, doc, XPathConstants.NODE);