Himanshu Yadav
Himanshu Yadav

Reputation: 13587

Reading and Updating XML string

I have text file with more than one XML documents in it. How can I parse this xml and update few of the element values.
There could be possibility when I have repeated element names in a single xml or multiple xmls in the same text file.In that case I would be referring to parent element value.
I looked into Java XPath API but it needs single XML document to parse. Here I have multiple xmls in a single file as a String.

Upvotes: 0

Views: 361

Answers (3)

Vitaly
Vitaly

Reputation: 2790

You can split them with "<?xml" or by the starting tag of each enclosed document so that you will have a set of well structured xml documents.

Then, you can create a chain of outputstreams and use technique to update the needed elements with SAX described in

Can we modify the XML file, like deleting,updating the nodes using SAX parser at run-time?

Insert new element to an XML file using SAX Filter

Upvotes: 1

vanje
vanje

Reputation: 10373

If you have multiple XML documents in one file you could either split the file into one XML document per file and parse each file separately. Or you can add a root node on your own to create a valid XML document.

Upvotes: 0

AllTooSir
AllTooSir

Reputation: 49362

A valid XML document must have a root element under which you can specify all other elements. It is a document where only ONE root element can be present. Read here , XML Specifications point 2.1 .

So , first try to convert the file into a valid XML document and then parse it using regular APIs. You have to read the entire file into a stream , prefix and suffix it with some <root> element and present that stream to a XML Parser.

Upvotes: 0

Related Questions