I have a xml document like this rootXMLDoc=<root> <param></param></root> . I need to insert paramxmlDoc= <parameter par='1'>abc</parameter>. how to insert paramxmlDoc to rootXMLDoc in java.? and i need output like this
<root>
<parameter par='1'>abc</parameter>
<param></param>
</root>
Like this:
Element e = paramxmlDoc.getRootElement();
paramxmlDoc.setRootElement(null); // break connection between doc and element
rootXMLDoc.getRootElement().addChild(e); // Insert node in other document
Note: This is from memory, so the actual method calls can be slightly different but you get the idea.
Related
When I am printing my API response, which gives me below xml as Response:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<BugInfo xmlns="ctessng" xmlns:ns2="http://www.w3.org/1999/xlink">
<Bug id="CSCvz53137">
<Field name="Assigned Date">09/01/2021 21:12:25</Field>
<Field name="Archived">N</Field>
<Field name="Assigner">James Vilson</Field>
<Field name="Status">V</Field>
<Field name="Submitter">Spark Mery</Field>
<Field name="Reason">Technically Inaccurate</Field>
<Field name="Regression">Y</Field>
<Field name="Resolved Date">09/02/2021 02:12:37</Field>
<Field name="Version">001.010</Field>
</Bug>
</BugInfo>
I want to fetch only specific values form this xml, like Assigned Date, Assigner, Submitter & Resolved-on
Assigned Date --> 09/01/2021 21:12:25
Assigner --> James Vilson
Submitter --> Spark Mery
Resolved Date --> 09/02/2021 02:12:37
What is the best/simplest way to read in values from this xml?
Regex
The most versatile would be plain text-filtering (match/find, extract) using a regular expression:
<Field name=\"(Assigned Date|Assigner|Submitter|Resolved Date)\">(.*)<
Iterating with find() then group(1) and group(2) can give you the desired strings.
See this regex demo
XPath
The pure XML-parsing way would be to use any XML parser, like DocumentBuilderFactory and SAXParser which can be used to read the XML into a document, then find the desired XML-nodes (Field elements) via XPath expression:
/BugInfo/Bug/Field[#name="Assigner"]|//Field[#name="Assigned Date"]|//Field[#name="Submitter"]|//Field[#name="Resolved Date"]
Iterating over the found nodes we can extract the child as text value.
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xPath.compile(xPathExpression).evaluate(xmlDocument, XPathConstants.NODESET);
See:
Filtering XML Document using XPATH in java
XPath OR operator for different nodes
XML mapping
The object-oriented way would use an XML mapper like Jackson to deserialize (unmarshall) the XML to an object.
Similar to the OkHTTP Recipe: Parse a JSON Response With Moshi (.kt, .java)
Then you would need a class where you can map the XML nodes to.
class Bug {
String submitter;
String assigner;
Date assignedOn;
Date resolvedOn
}
The mapping can be a bit tricky here, because from XML-model point-of-view a Bug node contains a collection of children Fields. But the target type, is semantically not a field-list, but a Bug-object with different typed properties.
This is probably the cleanest because it will be easy to parse: Bug bug = new XmlMapper().readValue(xmlString, Bug.class).
I am using Java to extract values using XPath. I was able to extract elements under the element fields but the elements under records are not returned.
XML is as follows:
<?xml version="1.0" ?>
<qdbapi>
<action>****</action>
<errcode>0</errcode>
<errtext>No error</errtext>
<qid>****</qid>
<qname>****</qname>
<table>
<fields>
<field id="19" field_type="text" base_type="text">
</field>
</fields>
<records>
<record>
<f id="6">1</f>
</record>
</records>
</table>
</qdbapi>
Code below:
XMLDOMDocObj.selectNodes("//*[local-name()='fields']")//21 fields returned
XMLDOMDocObj.selectNodes("//*[local-name()='records']")//no records are returned
XML must have a single root element; yours has two: fields and records.
Wrap them in a single common root to get the results you expect.
Also, if your XML has no namespaces, there's no reason to defeat them. Instead of
//*[local-name()='records']
use
//records
See also
How does XPath deal with XML namespaces?
Why must XML documents have a single root element?
What is the difference between root node, root element and document element in XML?
I have One XML Like
<root>
<name id="1">Abc</name>
<salary>25000</salary>
</root>
I want something like this
<root>
<name id="1,2">Abc</name>
<salary>25000</salary>
</root>
I am able to create the attribute by using DOM parser as:
Document doc = _docBuilder.newDocument();`
Attr attr = doc.createAttribute("id");
attr.setValue("1");
name.setAttributeNode(attr);
How can I get multiple attribute values for the same attribute.
XML does not support attributes with multiple values.
You could certainly do: attr.setValue("1,2");
However that really isn't very XML friendly. Also, you probably shouldn't have more than one value for an id. You may wish to consider something like this:
<thing>
<name>Abc</name>
<reference_ids>
<id>1</id>
<id>2</id>
</reference_ids>
</thing>
I have an XML, for example
<root>
<config x="xxx" y="yyyy" z="zzz" />
<properties>blah blah blah </properties>
<example>
<name>...</name>
<decr>...</descr>
</example>
<example>
<name>...</name>
<decr>...</descr>
</example>
</root>
and I need to get nodes config, and properties and all values in it.
Thank you
Xpath can fetch you the data in the config tag. You need to create an expression first like this
expression="//root/config/#x", to get value of x,y,z.
For properties, follow this thread :
Parsing XML with XPath in Java
Hope this helps
DOM,DOM4J,SAX..
if the size of XML file is small,you can use DOM or DOM4J,but the size is big , you use the SAX
If you directly want to query or fetch data XPath can help, but if you want the data as Java Objects so that you can use it further then use JAXB
You can use SAX parser to read the xml manipulate its event based parsing and consumes more memory.
If your xml is big and requires lot of manipulations then go-for DOM/DOM4j either is good. DOM4L is very latest. DOM is widely used in industry.
Based on your requirement go for good parser.
Thanks,
Pavan
I have the following xml:
<config xmlns="http://www.someurl.com">
<product>
<brand>
<content />
</brand>
</product>
</config>
I'm reading it nicely into JDOM.
However, when I try to use Jaxen to grab the contents, I can't seem to get anything.
Here's an example of what doesn't seem to work:
XPath xpath = new JDOMXPath("config");
SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
namespaceContext.addNamespace("", "http://www.someurl.com");
xpath.setNamespaceContext(namespaceContext);
assert xpath.selectNodes(document).size() > 0 : "should find more than 0";
This assertion always fails.
What am I doing wrong?
You have to assign a prefix. Make that call addNamespace("hopfrog", "http://...");
Then make the XPath ("hopfrog:config");
Keep in mind that the prefixes in XML aren't part of the real data model. The real data model assigns a URL, possibly blank, to each element and attribute. You can use any prefix you want in XPath so long as it's bound to the right URL. Since the URL you want it blank, you bind a prefix to 'blank'.