Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml search element by id

Can we search a element by id in xml file using dom parser, for example :

<root>
  <context id="one">
    <entity>
      <identifier>new one</identifier>
    </entity>
  </context>

  <context id="two">
    <entity>
      <identifier>second one</identifier>
    </entity>
  </context>

</root>

I want a node with id = "one", my code

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));

Element ele = document.getElementById("one");

return null,

is there any other way?

like image 322
Mahender Singh Avatar asked May 04 '26 14:05

Mahender Singh


1 Answers

From the documentation for Document.getElementById

Note: Attributes with the name "ID" or "id" are not of type ID unless so defined.

The problem is the Document doesn't know that an attribute called id is an identifier unless you tell it. You need to set a schema on the DocumentBuilderFactory before you call newDocumentBuilder. That way the DocumentBuilder will be aware of the element types.

In the schema you will need something like this in the appropriate place:

<xs:attribute name="id" type="xs:ID"/> 
like image 75
wobblycogs Avatar answered May 06 '26 03:05

wobblycogs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!