Wednesday 15 April 2015

java - xml search element by id -


For example:

Can we find an element by id using the XML parser in the ID element, for example:

  & lt; Root & gt; & Lt; Reference ID = "One" & gt; & Lt; Unit & gt; & Lt; Identifier & gt; A new & lt; / Identifier & gt; & Lt; / Unit & gt; & Lt; / References & gt; & Lt; Reference ID = "Two" & gt; & Lt; Unit & gt; & Lt; Identifier & gt; The second one & lt; / Identifier & gt; & Lt; / Unit & gt; & Lt; / References & gt; & Lt; / Root & gt;   

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

  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance (); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder (); Document document = docBuilder.parse (new file ("filename.xml")); Element element = document. GetElementById ("A");   

Return blank,

Is there any other way?

  For note: Name "id" or "id "Are not attribute type IDs, unless it is defined.   

The problem is that the document does not know that a feature called an "identifier" called id unless you tell it . You must set a schema on DocumentBuilderFactory before calling newDocumentBuilder . Thus DocumentBuilder will know about element types.

In the schema, you will need in a suitable place like this:

  & lt; Xs: attribute name = "id" type = "x: id" />    

No comments:

Post a Comment