XML generation, element is being added incorrectly - java

I am writing a method which adds few element under the same root element in a loop but when I open the XML file it look like the first element is added correctly and the other ones are added under main element.
This is my method addStepElement():
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
document.getDocumentElement().normalize();
Element rootElement = null;
NodeList findRootElementList = document.getElementsByTagName("testDetails");
for(int iterator = 0; iterator < findRootElementList.getLength(); iterator++) {
Node node = findRootElementList.item(iterator);
if(node.getNodeName().equals("testDetails")) {
rootElement = (Element)node;
}
}
Element step = document.createElement("Step");
rootElement.appendChild(step);
step.setAttribute("Step", "className");
step.setAttribute("result", "PASS");
step.setAttribute("screenshot", "file.jpg");
step.setAttribute("input", "email");
step.setAttribute("element", "submit");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(file.getAbsolutePath()));
transformer.transform(source, result);
This is my output XML:
<Test>
<testDetails date="19-05-2016" testName="Test" time="11:24:14">
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
</testDetails>
</Test>
This is what I want to achieve:
<Test>
<testDetails date="19-05-2016" testName="Test" time="11:24:14">
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
</testDetails>
</Test>
I do my method in a loop:
for(int i = 0; i < 5; i++) {
addStepElement();
}
What do I do wrong?

There is nothing wrong with the code as it produces an equivalent XML.
Indentation makes XML easier to read by human eye, but it doesn't change the meaning of XML whatsoever. All <Step> elements in the first XML are children of <testDetails> just like those <Step> elements in the 2nd XML. No difference in XML point of view.

Related

Creating an intermediate graph from XML file of UML activity diagram in java

I have an XML generated for an UML activity diagram. I want to generate a tree structure for XML so I could find possible transition paths. Tried with DOMXML java parser but no results. I need to group activity as nodes and transitions as edges. Also attached XML file. enter image description herePlease help
Java Code
public class DomXMLParser {
public static void main(String[] args) throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
//DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
File fXmlFile = new File("C:/Projekte/activity.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
javax.xml.xpath.XPathExpression expr
= xpath.compile("//xmi:XMI[xmi:type ='uml:Activity']/name/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
Eclipse Modeling Framework (EMF) design to read UML models. I write a code to Read UML Class Diagram reading with EMF. You design you model in Enterprise Architect so export as UMl model or design in papyrus which build on EMF
<?xml version="1.0" encoding="windows-1252"?>
<xmi:XMI xmi:version="2.1" xmlns:uml="http://schema.omg.org/spec/UML/2.1" xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmlns:StandardProfileL2="http://www.omg.org/spec/UML/20110701/StandardProfileL2.xmi">
<xmi:Documentation exporter="Enterprise Architect" exporterVersion="6.5"/>
<uml:Model xmi:type="uml:Model" name="EA_Model" visibility="public">
<packagedElement xmi:type="uml:Package"xmi:id="EAPK_263A2FE8_8346_4d1e_A851_39B9D573143D" name="Activity Model" visibility="public">
<ownedComment xmi:type="uml:Comment" xmi:id="EAID_DDCEE555_5FD6_487c_BB82_A5F055D67309" body="Case 3: Btn_Pressed = 3">
<annotatedElement xmi:idref="EAID_367AB5AB_2A9C_4387_B4A2_2974CE57D11E"/>
</ownedComment>
<packagedElement xmi:type="uml:Activity" xmi:id="EAID_A165F2B1_D71E_4c10_8EB4_745B37742C0F" name="Start CnrtLk_Main()" visibility="public" isReadOnly="false" isSingleExecution="false"/>
<edge xmi:type="uml:ControlFlow" xmi:id="EAID_5350396C_9C67_4190_817C_9EEF1E34582C" visibility="public" source="EAID_A165F2B1_D71E_4c10_8EB4_745B37742C0F" target="EAID_6428B619_8065_4a57_99CD_8F19CFB6F136"/>
<packagedElement xmi:type="uml:Activity" xmi:id="EAID_6428B619_8065_4a57_99CD_8F19CFB6F136" name="Get Parameters" visibility="public" isReadOnly="false" isSingleExecution="false"/>
<edge xmi:type="uml:ControlFlow" xmi:id="EAID_A0B50908_8ADF_4507_8033_E77D777E21DD" visibility="public" source="EAID_6428B619_8065_4a57_99CD_8F19CFB6F136" target="EAID_32296133_1810_41c5_9A4D_6D3B6F11FF52"/>
<node xmi:type="uml:InitialNode" xmi:id="EAID_CF9A7618_F1C4_4395_94D5_D2F483A51119" name="System_Initial" visibility="public">
<outgoing xmi:idref="EAID_2785D6B4_D4DF_442f_AF8B_657D85367743"/>
</node>
<node xmi:type="uml:ActivityFinalNode" xmi:id="EAID_D2EB427B_3AFD_4700_BD72_13B36684E595" name="ActivityFinal" visibility="public">
<incoming xmi:idref="EAID_E036A3F5_4C88_4471_9C2F_031554144E9E"/>
<incoming xmi:idref="EAID_D62F8934_F4E6_4b00_A35B_E1149E4C06E6"/>
<incoming xmi:idref="EAID_CC1E7F54_9C97_4aec_AE53_55AD4DA43408"/>
<incoming xmi:idref="EAID_ADD5D207_728A_4aeb_80EB_F9542CF6ED80"/>
<incoming xmi:idref="EAID_873CF8C4_0192_4099_8F66_6B36FA760AB6"/>
<incoming xmi:idref="EAID_6B8D52FB_C522_4bda_BE10_B5080F9F0B0D"/>
<incoming xmi:idref="EAID_417A863C_D59C_4c5e_8F38_60B1DC36B077"/>
</node>
<node xmi:type="uml:DecisionNode" xmi:id="EAID_0D85B784_4393_429e_9BA1_7983BD7891CA" name="decision1" visibility="public">
<incoming xmi:idref="EAID_1FAD9B0B_04ED_4f6a_B359_8755C3A3CA03"/>
<outgoing xmi:idref="EAID_32A43FB9_D99D_4c3c_8382_D899FD995BA7"/>
<outgoing xmi:idref="EAID_2FECE2AE_6CA0_48a4_82AE_D743D257F37C"/>
</node>
</packagedElement>
</packagedElement>

Split unsymmetrical XML into multiple XMLs

I have to split an unsymmetrical xml on 'Trade' element using java
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<BookingRequest>
<Id>1234</Id>
<App>Pan</App>
<Parties>
<Party>1</Party>
<Party>2</Party>
</Parties>
<Contract>
<Trades>
<Trade>
<Detail>100</Detail>
<Location>
<Num>10001</Num>
</Location>
</Trade>
<Trade>
<Detail>101</Detail>
<Location>
<Num>10002</Num>
</Location>
</Trade>
</Trades>
</Contract>
</BookingRequest>
My requirement is post split there should be 2 files:
FILE 1:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<BookingRequest>
<Id>1234</Id>
<App>Pan</App>
<Parties>
<Party>1</Party>
<Party>2</Party>
</Parties>
<Contract>
<Trades>
<Trade>
<Detail>100</Detail>
<Location>
<Num>10001</Num>
</Location>
</Trade>
</Trades>
</Contract>
</BookingRequest>
FILE 2:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<BookingRequest>
<Id>1234</Id>
<App>Pan</App>
<Parties>
<Party>1</Party>
<Party>2</Party>
</Parties>
<Contract>
<Trades>
<Trade>
<Detail>101</Detail>
<Location>
<Num>10002</Num>
</Location>
</Trade>
</Trades>
</Contract>
</BookingRequest>
Could someone help me in doing this kind of splitting (preferably using DOM/XPath and NOT XSLT)
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse("booking-request.xml");
Element bookingRequest = doc.getDocumentElement();
Element contract = (Element)bookingRequest.getElementsByTagName("Contract").item(0);
Element trades = (Element)contract.getElementsByTagName("Trades").item(0);
List<Element> tradeList = new ArrayList<Element>();
NodeList nodeList = trades.getElementsByTagName("Trade");
for(int i=0; i<nodeList.getLength(); i++)
tradeList.add((Element)nodeList.item(i));
Transformer transformer = TransformerFactory.newInstance().newTransformer();
int i = 0;
for(Element trade: tradeList){
// remove all children of <Trades>
while(trades.getFirstChild()!=null)
trades.removeChild(trades.getFirstChild());
trades.appendChild(doc.createTextNode("\n "));
trades.appendChild(trade);
trades.appendChild(doc.createTextNode("\n "));
++i;
transformer.transform(new DOMSource(doc), new StreamResult(new File("trade"+i+".xml")));
}

Java code for parsing a complex XML file

Below is a program written to parse the accompanying XML file.
Problem: There are two lane-IDs, but the output of my code keeps outputting only one. I expect the output to be:
Current Element: detector-report
Detector ID : I-74 NB from 12th Ave to 7th Ave
Status : operational
Lane-ID : 1
Lane - ID: 2
The current code still outputs 1 on the last line.
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class FinalTrial {
public static void main(String argv[]) {
try {
File fXmlFile = new File("workFile_09282014 22-10-34c.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("detector-report");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Detector ID : " + eElement.getElementsByTagName("detector-id").item(0).getTextContent());
System.out.println("Status : " + eElement.getElementsByTagName("status").item(0).getTextContent());
NodeList lanes = eElement.getElementsByTagName("lane");
System.out.println(lanes.getLength());
for (int j = 0; j<lanes.getLength(); j++) {
Element lane = (Element) lanes.item(0);
System.out.println("Lane-ID : " + lane.getElementsByTagName("lane-id").item(0).getTextContent());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Below is the accompanying XML file:
<?xml version="1.0" encoding="utf-8"?>
<trafficDetectorData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.dummy-temp-address" xmlns:lrms="http://www.dummy-lrms-address" xsi:schemaLocation="http://www.dummy-temp-address C:\temp\test\Detectors.xsd">
<detector-report>
<detector-id>I-74 NB from Ave of the Cities t</detector-id>
<status>operational</status>
<lane>
<lane-id>1</lane-id>
<count>1</count>
<volume>1</volume>
<occupancy>0</occupancy>
<speed>122</speed>
<classes>
<class>
<class-id>Small</class-id>
<count>1</count>
<volume>1</volume>
</class>
<class>
<class-id>Medium</class-id>
</class>
<class>
<class-id>Large</class-id>
</class>
</classes>
</lane>
<lane>
<lane-id>2</lane-id>
<occupancy>0</occupancy>
<speed>137</speed>
<classes>
<class>
<class-id>Small</class-id>
</class>
<class>
<class-id>Medium</class-id>
</class>
<class>
<class-id>Large</class-id>
</class>
</classes>
</lane>
</detector-report>
<detector-report>
<detector-id>I-74 NB from 12th Ave to 7th Ave</detector-id>
<status>operational</status>
<lane>
<lane-id>1</lane-id>
<count>3</count>
<volume>3</volume>
<occupancy>3</occupancy>
<speed>100</speed>
<classes>
<class>
<class-id>Small</class-id>
<count>3</count>
<volume>3</volume>
</class>
<class>
<class-id>Medium</class-id>
</class>
<class>
<class-id>Large</class-id>
</class>
</classes>
</lane>
<lane>
<lane-id>2</lane-id>
<count>4</count>
<volume>4</volume>
<occupancy>3</occupancy>
<speed>116</speed>
<classes>
<class>
<class-id>Small</class-id>
<count>4</count>
<volume>4</volume>
</class>
<class>
<class-id>Medium</class-id>
</class>
<class>
<class-id>Large</class-id>
</class>
</classes>
</lane>
</detector-report>
</trafficDetectorData>
I urge most developers to use established libraries for XML document handling, to avoid errors such as not properly escaping attribute values.
Java's built-in XML parsing library works very well (org.w3c.dom.Document, etc...).

How to parse unconventional XML files

I have the need to take what I consider an "unconventional" XML file that I get in and convert it into what I consider "conventional". The below XML examples have been "scrubbed" of proprietary names/values.
Here is what the "unconventional" XML file looks like:
<?xml version="1.0" encoding="UTF-8"?>
<dataView name="document/aDocument" xmlns="http://component.mycompany.com/entity/ds" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<dataItems>
<dataItem name="item1" location="item1" dataItemType="Long">
<value xsi:type="xs:string">1</value>
</dataItem>
<dataItem name="item2" location="item.seconditem(some item).ref" dataItemType="String">
<value xsi:type="xs:string">ABC2DEF3</value>
</dataItem>
</dataItems>
<dataRepeaters>
<dataRepeater name="SomeLevel1" runtimeInfomration="SomeLevel11984371030">
<dataGroups>
<dataGroup name="SomeLevel2" location="SomeLevel:(a level).thelevel" keyValue="SomeLevel119843710300" runtimeInformation="19843710300">
<dataItems>
<dataItem name="someItem1" location="someLevel.aLevel(another item)" dataItemType="String">
<value xsi:type="xs:string">12345</value>
</dataItem>
<dataItem name="someItem2" location="someLevel.aLevel(another item2)" dataItemType="Integer"/>
<dataItem name="someItem3" location="someLevel.aLevel(another item3)" dataItemType="ObjectReference">
<value xsi:type="xs:string">11:20012:3536</value>
</dataItem>
<dataItem name="someItem4" location="someLevel.aLevel(another item4)" dataItemType="String"/>
<dataItem name="someItem5" location="someLevel.aLevel(another item5)" dataItemType="String">
<value xsi:type="xs:string">someItem5 Data</value>
</dataItem>
<dataItem name="someItem6" location="someLevel.aLevel(another item6)" dataItemType="CurrencyAmount">
<value xsi:type="xs:string">123456:USD</value>
</dataItem>
</dataItems>
</dataGroup>
<dataGroup name="SomeLevel3" keyValue="SomeLevel31984371030" runtimeInformation="1984371030">
<dataRepeaters>
<dataRepeater name="SomeLevel4" runtimeInfomration="SomeLevel4">
<dataGroups>
<dataGroup name="SomeLevel5" location="anotherLevel.level5(SomeLevel5):someLevel5" keyValue="SomeLevel51984371030-11521863690" runtimeInformation="1984371030-11521863690">
<dataItems>
<dataItem name="someItem6" location="someLevel.aLevel(another item6)" dataItemType="BigDecimal">
<value xsi:type="xs:string">303.149</value>
</dataItem>
<dataItem name="someItem7" location="someLevel.aLevel(another item7)" dataItemType="CurrencyAmount">
<value xsi:type="xs:string">117:USD</value>
</dataItem>
<dataItem name="someItem8" location="someLevel.aLevel(another item8)" dataItemType="String">
<value xsi:type="xs:string">117.000000:USD</value>
</dataItem>
<dataItem name="someItem9" location="someLevel.aLevel(another item9)" dataItemType="CurrencyAmount">
<value xsi:type="xs:string">117:USD</value>
</dataItem>
</dataItems>
<dataRepeaters>
<dataRepeater name="SomeLevel6" runtimeInfomration="someLevel6">
<dataGroups/>
</dataRepeater>
</dataRepeaters>
</dataGroup>
<dataGroup name="SomeLevel7" location="anotherLevel.level5(SomeLevel7):someLevel7" keyValue="SomeLevel71984371030-11521863690" runtimeInformation="1984371030-11521863690">
<dataItems>
<dataItem name="someItem10" location="someLevel.aLevel(another item10)" dataItemType="BigDecimal">
<value xsi:type="xs:string">292.741</value>
</dataItem>
<dataItem name="someItem11" location="someLevel.aLevel(another item11)" dataItemType="CurrencyAmount">
<value xsi:type="xs:string">165:USD</value>
</dataItem>
<dataItem name="someItem12" location="someLevel.aLevel(another item12)" dataItemType="String">
<value xsi:type="xs:string">165.000000:USD</value>
</dataItem>
<dataItem name="someItem13" location="someLevel.aLevel(another item13)" dataItemType="CurrencyAmount">
<value xsi:type="xs:string">165:USD</value>
</dataItem>
</dataItems>
<dataRepeaters/>
</dataGroup>
<dataGroup name="SomeLevel8" location="anotherLevel.level5(SomeLevel8):someLevel8" keyValue="SomeLevel81984371030-11521863690" runtimeInformation="1984371030-11521863690">
<dataItems>
<dataItem name="someItem14" location="someLevel.aLevel(another item14)" dataItemType="BigDecimal">
<value xsi:type="xs:string">369.075</value>
</dataItem>
<dataItem name="someItem15" location="someLevel.aLevel(another item15)" dataItemType="CurrencyAmount">
<value xsi:type="xs:string">598:USD</value>
</dataItem>
<dataItem name="someItem16" location="someLevel.aLevel(another item16)" dataItemType="String">
<value xsi:type="xs:string">598.000000:USD</value>
</dataItem>
</dataItems>
<dataRepeaters>
<dataRepeater name="SomeLevel9" runtimeInfomration="someLevel9">
<dataGroups>
<dataGroup name="SomeLevel10" location="ownedAuto.AgreementActual(Liability).ConstantRole(Policy Form):policyForm" keyValue="aomeLevel101984371030-11521863690-115218636900" runtimeInformation="1984371030-11521863690-115218636900">
<dataItems>
<dataItem name="someItem17" location="someLevel.aLevel(another item17)" dataItemType="String">
<value xsi:type="xs:string">Some Data | ABC 123</value>
</dataItem>
<dataItem name="someItem18" location="someLevel.aLevel(another item18)" dataItemType="Integer">
<value xsi:type="xs:string">2</value>
</dataItem>
</dataItems>
</dataGroup>
</dataGroups>
</dataRepeater>
<dataRepeater name="SomeLevel10" runtimeInfomration="someLevel11">
<dataGroups/>
</dataRepeater>
</dataRepeaters>
</dataGroup>
</dataGroups>
</dataRepeater>
</dataRepeaters>
</dataGroup>
</dataGroups>
</dataRepeater>
</dataRepeaters>
</dataView>
I am trying to convert it to something like this:
<?xml version="1.0" encoding="UTF-8"?>
<dataView name="document/aDocument" xmlns="http://component.mycompany.com/entity/ds" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<item1>1</item1>
<item2>ABC2DEF3</item2>
<SomeLevel1>
<SomeLevel2>
<someItem1>12345f</someItem1>
<someItem2></someItem2>
<someItem3>11:20012:3536</someItem3>
<someItem4>12345f</someItem4>
<someItem5>someItem5 Data</someItem5>
<someItem6>123456:USD</someItem6>
</SomeLevel2>
<SomeLevel3>
<SomeLevel4>
<SomeLevel5>
<someItem7>303.149</someItem7>
<someItem8>117:USD</someItem8>
<someItem9>117.000000:USD</someItem9>
<someItem10>117:USD</someItem10>
<SomeLevel6></SomeLevel6>
</SomeLevel5>
<SomeLevel7>
<someItem11>292.741</someItem11>
<someItem12>165:USD</someItem12>
<someItem13>165.000000:USD</someItem13>
<someItem14>165:USD</someItem14>
</SomeLevel7>
<SomeLevel8>
<someItem15>369.075</someItem15>
<someItem16>598:USD</someItem16>
<someItem17>598.000000:USD</someItem17>
<SomeLevel9>
<SomeLevel10>
<someItem18>Some Data | ABC 123</someItem18>
<someItem19>2</someItem19>
</SomeLevel10>
</SomeLevel9>
<SomeLevel11></SomeLevel11>
</SomeLevel8>
</SomeLevel4>
</SomeLevel3>
</SomeLevel1>
</dataView>
So basically I am trying to take the "name" attribute and make it the XML node/tag and the value between the <value> node/tag and use it as the "value" for the XML node/tag.
I have tried several different parsing/writing "routines" and the below two are the two that have gotten me the closest. So I'm leaving out the other ones as they would be just "noise".
Here is what I have tried so far:
private Document xmlDocument;
public void convertXML() {
xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("DSExample.xml")));
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Node dsNode = xmlDocument.getDocumentElement();
xmlDocument = docBuilder.newDocument();
// Attempt 1:
doSomethingDS(dsNode); // This will convert the XML but with NO nesting - creates example output 1
// Attempt 2:
traverseDS(dsNode); // This will create an XML with ONLY the root dataItems - Don't know why - creates example output 2
}
public void doSomethingDS(Node node) {
System.out.println(node.getNodeName());
Element xmlElement = null;
// This will be the "root" element/node "dataView":
if(node.getNodeName() != null && node.getNodeName().equalsIgnoreCase("dataView")) {
// Debugging: Print the node
printNode(node);
String nodeName = node.getNodeName().trim();
rootElement = xmlDocument.createElement(nodeName);
mPreviousElement = rootElement;
addAllAttributesToRootElement((Element) node, rootElement);
xmlDocument.appendChild(rootElement);
}
else {
// Debugging: Print the node
printNode(node);
// If has "name" property - create element/node
if(node.getAttributes() != null && node.getAttributes().getNamedItem("name") != null) {
xmlElement = createElement(xmlDocument, node);
if(xmlElement !=null && xmlDocument.getFirstChild() != null) {
xmlDocument.getFirstChild().appendChild(xmlElement);
}
}
}
NodeList nodeList = node.getChildNodes();
for(int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if(currentNode.getNodeType() == Node.ELEMENT_NODE) {
// recursively call this method for all the children which are of type Element
doSomethingDS(currentNode);
}
}
} // End of doSomethingDS()
public void traverseDS(Node parentNode) {
// This will create an XML with ONLY the root dataItems - Don't know why.
Element xmlElement = null;
//****************************************************************
// This will be the "root" element/node "dataView":
if(parentNode.getNodeName() != null && parentNode.getNodeName().equalsIgnoreCase("dataView")) {
// Debugging: Print the node
printNode(parentNode);
String nodeName = parentNode.getNodeName().trim();
rootElement = xmlDocument.createElement(nodeName);
mPreviousElement = rootElement;
if(!isRootNodeSet) {
mRootNode = parentNode;
isRootNodeSet = true;
}
addAllAttributesToRootElement((Element) parentNode, rootElement);
xmlDocument.appendChild(rootElement);
// traverse children
Node theNode = parentNode.getFirstChild();
if(theNode != null) {
theNode = theNode.getNextSibling();
}
else if (isRootNodeSet) {
theNode = mRootNode.getNextSibling();
}
traverseDS(theNode);
}
else {
// traverse all nodes that belong to the parent
for(Node theNode = parentNode.getFirstChild(); theNode != null; theNode = theNode.getNextSibling()) {
// Debugging: Print the node
printNode(theNode);
// If has "name" property - create element/node
if(theNode.getAttributes() != null && theNode.getAttributes().getNamedItem("name") != null) {
// Create new Element/Node
xmlElement = createElement(xmlDocument, theNode);
if(xmlElement !=null && xmlDocument.getFirstChild() != null) {
xmlDocument.getFirstChild().appendChild(xmlElement);
}
else {
System.out.println(" not a node we wanted?");
}
}
// traverse children
traverseDS(theNode);
}
}
} // End of traverseDS()
private Element createElement(Document aDoc, Node aNode) {
Element xmlElement = null;
String elementName = "";
NamedNodeMap dataNodeMap = aNode.getAttributes();
if(dataNodeMap != null && dataNodeMap.getNamedItem("name") != null) {
elementName = dataNodeMap.getNamedItem("name").getTextContent();
xmlElement = aDoc.createElement(elementName);
// if node = "dataItem" - walk node to get <value> node
// Note: some "dataItem" nodes also have a <previousValue> node - what to do with these????
if(aNode.getNodeName() != null && aNode.getNodeName().equalsIgnoreCase("dataItem")) {
// Walk Node to get <value> node
NodeList childNodes = aNode.getChildNodes();
int childNodesLength = childNodes.getLength();
for(int x = 0; x < childNodesLength; x++) {
Node childNode = childNodes.item(x);
if(childNode.getNodeName() != null && childNode.getNodeName().equalsIgnoreCase("value")) {
xmlElement.setTextContent(childNode.getTextContent());
break;
}
}
}
}
return xmlElement;
} // End of createElement()
Example Output 1 (created by doSomethingDS()):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<dataView xmlns="http://component.mycompany.com/entity/ds" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="document/aDocument">
<item1>1</item1>
<item2>ABC2DEF3</item2>
<SomeLevel1/>
<SomeLevel2/>
<someItem1>12345</someItem1>
<someItem2/>
<someItem3>11:20012:3536</someItem3>
<someItem4/>
<someItem5>someItem5 Data</someItem5>
<someItem6>123456:USD</someItem6>
<SomeLevel3/>
<SomeLevel4/>
<SomeLevel5/>
<someItem6>303.149</someItem6>
<someItem7>117:USD</someItem7>
<someItem8>117.000000:USD</someItem8>
<someItem9>117:USD</someItem9>
<SomeLevel6/>
<SomeLevel7/>
<someItem10>292.741</someItem10>
<someItem11>165:USD</someItem11>
<someItem12>165.000000:USD</someItem12>
<someItem13>165:USD</someItem13>
<SomeLevel8/>
<someItem14>369.075</someItem14>
<someItem15>598:USD</someItem15>
<someItem16>598.000000:USD</someItem16>
<SomeLevel9/>
<SomeLevel10/>
<someItem17>Some Data | ABC 123</someItem17>
<someItem18>2</someItem18>
<SomeLevel11/>
</dataView>
Example Output 2 (Created by traverseDS()):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<dataView xmlns="http://component.mycompany.com/entity/ds" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="document/aDocument">
<item1>1</item1>
<item2>ABC2DEF3</item2>
</dataView>
Now here is that catch.... What I get is dynamic I could get a Mac truck one time and a Toyota the next or a mixture of the two. And the size of the XML I get could be small or large. So it's hard to just use XPath or directly go after specific elements as I don't know what I'll get. This is why I'm basically walking/traversing the DOM a node at a time to extract out just what is useable.
So my question is:
What am I doing wrong in my parsing/writing of the XML file to not get it to look like what I'm trying to get it to look like?
This is (almost) trivially easy with XSLT:
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ds="http://component.mycompany.com/entity/ds"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://component.mycompany.com/entity/ds"
>
<xsl:output indent="yes" />
<xsl:strip-space elements="*" />
<xsl:template match="ds:dataView" priority="1">
<xsl:copy>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match="ds:*[#name]">
<xsl:element name="{#name}">
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space()" />
</xsl:template>
</xsl:stylesheet>
applied do your input, gives you:
<dataView xmlns="http://component.mycompany.com/entity/ds" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<item1>1</item1>
<item2>ABC2DEF3</item2>
<SomeLevel1>
<SomeLevel2>
<someItem1>12345</someItem1>
<someItem2 />
<someItem3>11:20012:3536</someItem3>
<someItem4 />
<someItem5>someItem5 Data</someItem5>
<someItem6>123456:USD</someItem6>
</SomeLevel2>
<SomeLevel3>
<SomeLevel4>
<SomeLevel5>
<someItem6>303.149</someItem6>
<someItem7>117:USD</someItem7>
<someItem8>117.000000:USD</someItem8>
<someItem9>117:USD</someItem9>
<SomeLevel6 />
</SomeLevel5>
<SomeLevel7>
<someItem10>292.741</someItem10>
<someItem11>165:USD</someItem11>
<someItem12>165.000000:USD</someItem12>
<someItem13>165:USD</someItem13>
</SomeLevel7>
<SomeLevel8>
<someItem14>369.075</someItem14>
<someItem15>598:USD</someItem15>
<someItem16>598.000000:USD</someItem16>
<SomeLevel9>
<SomeLevel10>
<someItem17>Some Data | ABC 123</someItem17>
<someItem18>2</someItem18>
</SomeLevel10>
</SomeLevel9>
<SomeLevel10 />
</SomeLevel8>
</SomeLevel4>
</SomeLevel3>
</SomeLevel1>
</dataView>
Notes:
Having numbered element names (someItem1 thru someItem6) will come back and bite you, eventually. XML elements have a natural order (or you can have a "number" attribute), putting a counter into the name is bad and wrong. Take my advice and don't do that (*).
To understand the solution here's a quick breakdown:
XSLT processors run XML nodes through templates by finding the best match for the XML node at hand.
The process starts with the root node.
Since there is no template explicitly matching the root node (<xsl:template match="/">), a default rule kicks in: Output nothing, but find templates for the child nodes.
The first (and only) child node is the document element (<ds:dataView>).
The template #1 matches that node, tells the processor to copy it and process its children (<xsl:apply-templates />).
Every element that has a #name is matched by template #2, which outputs an element with that name and again processes its children.
Every other element (like those <value> nodes) is - in the absence of any matching template - processed according to the mentioned default rule.
Text nodes are matched by template #3, which outputs their trimmed value.
Additional notes:
The expression in curly braces is called an attribute value template.
The template priority="1" makes sure that this template is selected for the <ds:dataView> element, because the other one would match as well.
Your result document still is in the "http://component.mycompany.com/entity/ds". This might or might not be correct. I suspect it's not correct, technically speaking, but you decide.
(*) <xsl:element name="{translate(#name, '0123456789', '')}" would be one variant to lose the counters.
XSLT has been created exactly for a task like that. As long as your Source-XML (unconventional xml) is well-formed (correct xml-syntax) so that it can be read by a standard xml-parser like DOM, you can use that.
It works like so: You create a xsl-template file that contains a declerative description how the source xml should be transformed into another format. The transformation itself is done by a XSL-Transformer.
The xsl is also an xml-format, so it should be quit easy readable, as long as the transformation is not too complex.
Here is explained how that can be implemented:
http://docs.oracle.com/javase/tutorial/jaxp/xslt/transformingXML.html

Add new element to xml file with Java DOM

I have been working with a simple cd catalog XML file:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG>
With this method I want to create a new CD element:
private static void addCd(File xml) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, SAXException, IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(xml);
Element cd = document.createElement("CD");
document.appendChild(cd);
for (int i = 1; i <= 3; i++) {
Element title = document.createElement("TITLE");
Element artist = document.createElement("ARTIST");
Element country = document.createElement("COUNTRY");
Element company = document.createElement("COMPANY");
Element price = document.createElement("PRICE");
Element year = document.createElement("YEAR");
title.appendChild(document.createTextNode("mike "));
artist.appendChild(document.createTextNode("oconnor "));
country.appendChild(document.createTextNode("ie "));
company.appendChild(document.createTextNode("dell "));
price.appendChild(document.createTextNode("14 "));
year.appendChild(document.createTextNode("2014 "));
cd.appendChild(title);
cd.appendChild(artist);
cd.appendChild(country);
cd.appendChild(company);
cd.appendChild(price);
cd.appendChild(year);
}
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File("cdCatalog.xml"));
transformer.transform(domSource, streamResult);
DOMSource source = new DOMSource(document);
}
I can create a new CD element, but the new element appears outside my root (<CATALOG>) element:
<?xml version="1.0" encoding="utf-8" standalone="no"?><CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG><CD><TITLE>mike </TITLE><ARTIST>oconnor </ARTIST><COUNTRY>ie </COUNTRY><COMPANY>dell </COMPANY><PRICE>14 </PRICE><YEAR>2014 </YEAR><TITLE>mike </TITLE><ARTIST>oconnor </ARTIST><COUNTRY>ie </COUNTRY><COMPANY>dell </COMPANY><PRICE>14 </PRICE><YEAR>2014 </YEAR><TITLE>mike </TITLE><ARTIST>oconnor </ARTIST><COUNTRY>ie </COUNTRY><COMPANY>dell </COMPANY><PRICE>14 </PRICE><YEAR>2014 </YEAR></CD>
I think I appended the wrong element, but have no idea how to append to CATALOG.
The problem is, you were append element by document, YOU needs to append CD by root element
Try like this:
...
Document document = db.parse(xml);
Element root = document.getDocumentElement();
Element cd = document.createElement("CD");
root.appendChild(cd);
.....
......
....
You should use the getElementsByTagName to get the first catalog tag and append your cd object to it, not to the document like you're doing.
You can use XML DOM editing features:
Java DOM

Categories

Resources