Delete TextContents of XML element before appending text - java

I am appending text to XML element iteratively like the following
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File("./myXML.xml")));
Element element = doc.getDocumentElement();
NodeList node1 = doc.getElementsByTagName("name");
Element fn= (Element) node1.item(0);
Text text = doc.createTextNode(Content);
fn.appendChild(text);
printtoXML(doc);
My printXML method is updating xml by using TransformerFactory
fn.setTextContent() method does not work here,Because in every iteration it setting old text to new text.
I want to append Text iteratively, and in my next execution i want to delete old text contents of the particular element and append it again.
I have to execute the program many times for my testing and i don't want to append the same text again and again....
Could you please help me to solve this problem..

this might work
Text text;
void callsomefunctionthousendtimes(){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File("./myXML.xml")));
text = doc.createTextNode("");
Element element = doc.getDocumentElement();
NodeList node1 = doc.getElementsByTagName("name");
Element fn= (Element) node1.item(0);
//TODO call your functionName(content) 1000 times here
fn.appendChild(text);
printtoXML(doc);
}
void functionName(String content){
text = text.replaceWholeText(text.getWholeText() + content);
}
added bonusus, only load the doc in once

Related

xml parse - xpath clarification in Java

How should i get the Link value from the below xml
XML Content
<document-instance system="abc.org" number-of-pages="6" desc="Drawing" link="www.google.com">
<document-format-options>
<document-format>application/pdf</document-format>
<document-format>application/tiff</document-format>
</document-format-options>
<document-section name="DRAWINGS" start-page="1" />
</document-instance>
i traverse update desc attribute after that i'm struggle
XPathExpression firstPageUrl = xPath.compile("//document-instance/#desc=\"Drawing\"]");
Expected output : retrieve the Link value
www.google.com
File file = new File("path to file");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//document-instance/#link";
Node node = (Node) xPath.compile(expression).evaluate(doc, XPathConstants.NODE);
String url= node.getTextContent();

Getting value of child node from XML in java

My xml file looks like this
<InNetworkCostSharing>
<FamilyAnnualDeductibleAmount>
<Amount>6000</Amount>
</FamilyAnnualDeductibleAmount>
<IndividualAnnualDeductibleAmount>
<NotApplicable>Not Applicable</NotApplicable>
</IndividualAnnualDeductibleAmount>
<PCPCopayAmount>
<CoveredAmount>0</CoveredAmount>
</PCPCopayAmount>
<CoinsuranceRate>
<CoveredPercent>0</CoveredPercent>
</CoinsuranceRate>
<FamilyAnnualOOPLimitAmount>
<Amount>6000</Amount>
</FamilyAnnualOOPLimitAmount>
<IndividualAnnualOOPLimitAmount>
<NotApplicable>Not Applicable</NotApplicable>
</IndividualAnnualOOPLimitAmount>
</InNetworkCostSharing>
I am trying to get Amount value from <FamilyAnnualDeductibleAmount> and also from <FamilyAnnualOOPLimitAmount>. How do i get those values in java?
You may use two XPath queries /InNetworkCostSharing/FamilyAnnualDeductibleAmount and InNetworkCostSharing/FamilyAnnualOOPLimitAmount or just get the node InNetworkCostSharing and retrieve the values of its two direct children.
Solution using XPath:
// load the XML as String into a DOM Document object
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream("YOUR XML".getBytes());
Document doc = docBuilder.parse(bis);
// XPath to retrieve the content of the <FamilyAnnualDeductibleAmount> tag
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/InNetworkCostSharing/FamilyAnnualDeductibleAmount/text()");
String familyAnnualDeductibleAmount = (String)expr.evaluate(doc, XPathConstants.STRING);
StAX based solution:
XMLInputFactory f = XMLInputFactory.newInstance();
XMLStreamReader rdr = f.createXMLStreamReader(new FileReader("test.xml"));
while (rdr.hasNext()) {
if (rdr.next() == XMLStreamConstants.START_ELEMENT) {
if (rdr.getLocalName().equals("FamilyAnnualDeductibleAmount")) {
rdr.nextTag();
int familyAnnualDeductibleAmount = Integer.parseInt(rdr.getElementText());
System.out.println("familyAnnualDeductibleAmount = " + familyAnnualDeductibleAmount);
} else if (rdr.getLocalName().equals("FamilyAnnualOOPLimitAmount")) {
rdr.nextTag();
int familyAnnualOOPLimitAmount = Integer.parseInt(rdr.getElementText());
System.out.println("FamilyAnnualOOPLimitAmount = " + familyAnnualOOPLimitAmount);
}
}
}
rdr.close();
Note that StAX is especially good for cases like yours, it skips all unnecessary elements reading only the ones you need
Try something like this(use getElementsByTagName to get the parent nodes and then get the value be reaching out to child node):
File xmlFile = new File("NetworkCost.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile );
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("FamilyAnnualDeductibleAmount");
String familyDedAmount = nList.item(0).getChildNodes().item(0).getTextContent();
nList = doc.getElementsByTagName("FamilyAnnualOOPLimitAmount");
String familyAnnualAmount =
nList.item(0).getChildNodes().item(0).getTextContent();
I think I found the solution with this question from stackoverflow
Getting XML Node text value with Java DOM

How to get namespace of xml

I have this xml:
InputStream is = new ByteArrayInputStream(
"<data:RobCtiAifoData xmlns:data=\"urn:cz:isvs:rob:schemas:RobDotazyData:v1\" xmlns:reg=\"urn:cz:isvs:reg:schemas:RegTypy:v1\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:cz:isvs:rob:schemas:RobUnivDotazy:v1\"><data:Aifo a=\"b\">1</data:Aifo><data:VyuzitiPoskytnuti>vyuziti</data:VyuzitiPoskytnuti> </data:RobCtiAifoData>"
.getBytes());
// InputStream is = new ByteArrayInputStream(xml.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(is);
Node node = document.getDocumentElement();
when wanna get name of element without namespace so I wanna call substring of name of element withou prefix
node.getNodeName() gives me data:VyuzitiPoskytnuti
and node.getNamespaceURI() or node.getPrefix() gives me just null. So how I can get prefix of node ?
Try enabling namespace support:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
From the JavaDoc for setNamespaceAware:
Specifies that the parser produced by this code will provide support for XML namespaces. By default the value of this is set to false

getElementsByTagName doesn't work

I have next simple part of code:
String test = "<?xml version="1.0" encoding="UTF-8"?><TT_NET_Result><GUID>9145b1d3-4aa3-4797-b65f-9f5e00be1a30</GUID></TT_NET_Result>"
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(test)));
NodeList nl = doc.getDocumentElement().getElementsByTagName("TT_NET_Result");
The problem is that I don't get any result - nodelist variable "nl" is empty.
What could be wrong?
You're asking for elements under the document element, but TT_NET_Result is the document element. If you just call
NodeList nl = doc.getElementsByTagName("TT_NET_Result");
then I suspect you'll get the result you want.
Here's another response to this old question. I hit a similar issue in my code today and I actually read/write XML all the time. For some reason I overlooked one major fact. If you want to use
NodeList elements = doc.getElementsByTagNameNS(namespace,elementName);
You need to parse your document with a factory that is namespace-aware.
private static DocumentBuilderFactory getFactory() {
if (factory == null){
factory = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(true);
}
return factory;
}

Attaching Node with null value to a DOM document

I am trying to attach a node to a DOM document in the example code shown below.
1)I initialized the nodes "title, type" to null.
2)I tried to append these above nodes to the Document "child_doc" and then tried to set a new value to these nodes.
But on doing the above, I am getting a java.lang.NullPointerException at this line:
child_doc.appendChild(title).setNodeValue("New" + childType);
How do I resolve this?
Thanks,
Sony
Example code:
public synchronized void attachNodeToParent1 (Element parent, String childType) throws ParserConfigurationException {
Document parent_doc = parent.getOwnerDocument();
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document child_doc = docBuilder.newDocument();
Element child = null;
Node title = null;
Node type = null;
child_doc.appendChild(title).setTextContent("New" + childType);
child_doc.appendChild(type).setTextContent(childType);
child = child_doc.getDocumentElement();
parent.appendChild(child);
}
Initialize them to proper elements:
Element title = child_doc.createElement("type");
Element type = child_doc.createElement("title);

Categories

Resources