XML Parsing / Dom Manipulation in Java

I am trying to figure out how best to translate this:

<Source><properties>
  ....
  <name>wer</name>
  <delay>
    <type>Deterministic</type>
    <parameters length="1">
      <param value="78" type="Time"/>
    </parameters>
  </delay>
  <batchSize>
    <type>Cauchy</type>
    <parameters length="2">
      <param value="23" type="Alpha"/>
  <param value="7878" type="Beta"/>
    </parameters>
  </batchSize>
 ...
</properties></Source>

AT:

<Source><properties>
  ....
  <name>wer</name>
  <delay>
    <Deterministic Time="78"/>
  </delay>
  <batchSize>
      <Cauchy Alpha="23" Beta="7878"/>
  </batchSize>
 ........
</properties></Source>

I tried to use DocumentBuilderFactory, but so far I can access the value of the name tag, I cannot access the values ​​in the delay / batch section. This is the code I used

Element prop = (Element)propertyNode;

NodeList nodeIDProperties = prop.getElementsByTagName("name");
Element nameElement = (Element)nodeIDProperties.item(0);

NodeList textFNList = nameElement.getChildNodes();
String nodeNameValue = ((org.w3c.dom.Node)textFNList.item(0)).getNodeValue().trim();

//--------
NodeList delayNode = prop.getElementsByTagName("delay");

Calling getElementByName ("type") or "parameters" does not return anything I can work with. I missed something, or is there a cleaner way to process existing xml.

You must be in a specific format to enable sorting and disassembly using Castor.

Any help would be greatly appreciated.

+3
source share
4 answers

There are many ways to convert XML.

1) XSLT (XSL Transformations) XML. , XML, XML XML-, HTML. . XML. - . XSLT Java Saxon, . , XSLT, , . , Java . , , .

2) XPath, . XPath - XML. , XPath XSLT. . XPath

//delay[type = 'Deterministic']/parameters/param/@value

value, node param, delay, node type "". - - XPath. - XPath Java XPath . XPath Java-. IMHO , DOM ( , ).

3) Smooks XML . , . Smooks XML XML Freemarker, XSL. Smooks , ESB (, JBoss ESB, Apache ServiceMix). , .

4) , Freemarker. , , , . . " XML" ( " XML" , , XML). . , .

+5

In the end, XSLT was straightforward. Its actually quite easy to use, and the w3schools example is a good place to start.

0
source

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


All Articles