如果您的id
属性是类型xs:ID
,并且您的文档有 XML 模式,那么您可以使用该Document.getElementById(String)
方法。我将在下面用一个例子来演示。
XML 模式
<?xml version="1.0" encoding="UTF-8"?>
<schema
xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/schema"
xmlns:tns="http://www.example.org/schema"
elementFormDefault="qualified">
<element name="foo">
<complexType>
<sequence>
<element ref="tns:bar" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
<element name="bar">
<complexType>
<attribute name="id" type="ID"/>
</complexType>
</element>
</schema>
XML 输入 (input.xml)
<?xml version="1.0" encoding="UTF-8"?>
<foo xmlns="http://www.example.org/schema">
<bar id="ABCD"/>
<bar id="EFGH"/>
<bar id="IJK"/>
</foo>
演示
您将需要设置Schema
on 的实例DocumentBuilderFactory
以使一切正常工作。
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.*;
import javax.xml.validation.*;
import org.w3c.dom.*;
public class Demo {
public static void main(String[] args) throws Exception {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("src/forum17250259/schema.xsd"));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setSchema(schema);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("src/forum17250259/input.xml"));
Element result = document.getElementById("EFGH");
System.out.println(result);
}
}