The most efficient way to process a string containing XML in JAVA

I have a String that contains XML nodes in it, and I'm trying to use DOM parsing to process this string to extract node values ​​and store them in local variables.

XML stored in String variable:

<carGarage>
   <car>
      <make>Chrysler</make>
      <color>Red</color>
   </car>
   <car>
      <make>Musano</make>
      <color>Blue</color>
   </car>
</carGarage>

My Java class is where I want to extract XML values ​​and store them in local attributes:

public class CarGarage
{   String make, color;

    public void setMake(String make)
    { this.make = make; }

    public void setColor(String color)
    { this.color = color; }

    public void DOMparsingMethod(Node thisNode)
    { int typeOfNode = thisNode.getNodeType();
      ...
    }
}

What is the best way to approach this? I looked at StringBufferInputStream, but this is deprecated. I really got lost.

Thankyou, Lucas.

+3
source share
5 answers

DocumentBuilder . , , , .

+2

xml, , , , , .

dom. Justinhj java , , jdk xml, , .

jdom . , DocumentBuilder, .

+1

XStream. XML . XML, , .

+1

In my experience, the DOM is useful for this kind of thing because it has a low learning curve compared to SAX / STAX, even though it is not so fast or efficient. When you have a DOM document, you can use XPath queries for the document to get the contents of individual elements and parse them.

0
source

Source: https://habr.com/ru/post/1708502/


All Articles