permaculture playing cards*
The moose likes XML and Related Technologies and the fly likes making changes to an xml document...help needed! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "making changes to an xml document...help needed!" Watch "making changes to an xml document...help needed!" New topic
Author

making changes to an xml document...help needed!

ahsan mir
Ranch Hand

Joined: Jul 17, 2006
Posts: 42
Hello,
i am fairly new to xml and am using it in my degree project.I am able to retrieve and read data from a fairly large xml file using JAXP(DOM) and/or XMLBeans.I am having difficulties in updating the xml document. Any updation i believe is ito be saved into a new xml document,but dont know how to proceed with it. Any help would be appreciated.


Following is a snippet of my code using JAXP. Here i am able to retrieve data from the source file.
////////////////////////////////////////////////////////////////
File document=new File("C:\\tester.xml");
try {
DocumentBuilderFactory factory
= DocumentBuilderFactory.newInstance();
DocumentBuilder parserr = factory.newDocumentBuilder();
Document doc=parserr.parse(document);
System.out.println(document + " is well-formed.");
NodeList n2=doc.getElementsByTagName("Top");
NodeList n3=doc.getElementsByTagName("Base");
int x=n2.getLength();
System.out.println("There are " +x +"players");
for(int g=0;g<=x;g++)
{
System.out.println("Top is" + n2.item(g).getFirstChild().getNodeValue()+" Base is" +n3.item(g).getFirstChild().getNodeValue());
}
}

///////////////////////////////////////////////////////////////////////////
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41034
    
  43
You seem to have mastered DOM, so I assume that changing the document in memory by Node.setNodeValue, Node.appendChild, Node.removeChild, Node.insertBefore etc. does not pose any problems. So I'm guessing it's the storing of the altered document that has you stumped? If you are using Java 5, then you can use the API described here.
[ October 26, 2006: Message edited by: Ulf Dittmer ]

Ping & DNS - my free Android networking tools app
ahsan mir
Ranch Hand

Joined: Jul 17, 2006
Posts: 42
Thanks,
it looks daunting, ill try it, surley there must be an easier way to do this. My append code is as follows :

//////////////////////////////////////////////////////////////////////////
NodeList list=doc.getElementsByTagName("Information");
for(int i=0; i<list.getLength();i++){
Node thissampnode=list.item(i);
Node thisNameNode=thissampnode.getFirstChild();
if(thisNameNode==null) continue;
if(thisNameNode.getFirstChild()==null)continue;
// if(thisNameNode.getFirstChild() !(instanceof org.w3c.dom.Text) continue;
String data=thisNameNode.getFirstChild().getNodeValue();
if (! data.equals("0.59")) continue;


Node newsampNode = doc.createElement("Samp");

Node newsampTopNode = doc.createElement("Top");
Text tnNode = doc.createTextNode("0.50");
newsampTopNode.appendChild(tnNode);

Element newsampRef = doc.createElement("Ref");
Text tsr = doc.createTextNode("0");
newsampRef.appendChild(tsr);

Element newsampType = doc.createElement("Type");
Text tt = doc.createTextNode("z");
newsampType.appendChild(tt);

Element newsampbase = doc.createElement("Base");
Text sb = doc.createTextNode("0.55");
newsampbase.appendChild(sb);


newsampNode.appendChild(newsampTopNode);
newsampNode.appendChild(newsampRef);
newsampNode.appendChild(newsampType);
newsampNode.appendChild(newsampbase);



rootNode.insertBefore(newsampNode, thissampnode);
////////////////////////////////////////////////////////////
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Before DOM level 3, the standard way was to use an identity transformation to transform the DOM to a file. (I know, not exactly the most intuitive approach!) Like this:
ahsan mir
Ranch Hand

Joined: Jul 17, 2006
Posts: 42
hello,
i have tried using the transformation example, but still cant get it going.I have used an example of a book here. I can get the data in the new xml file but with no changes i.e. the new xml file is a replica of the original xml file.
Any help would be appreciated.
Following is the code:

***************************************************************
public static void main(String args[])
{
File document=new File("C://examplebook.xml");
try
{
DocumentBuilderFactory factory
= DocumentBuilderFactory.newInstance();
DocumentBuilder parserr = factory.newDocumentBuilder();
Document doc=parserr.parse(document);
Element personNode=doc.createElement("person");

Element nameNode=doc.createElement("name");
personNode.appendChild(nameNode);
Text nametextNode=doc.createTextNode("Laany simpson");
nameNode.appendChild(nametextNode);

Element phoneNode=doc.createElement("phone");
personNode.appendChild(phoneNode);
Text phonetextNode=doc.createTextNode("07897698789");
phoneNode.appendChild(phonetextNode);

Element emailNode=doc.createElement("email");
personNode.appendChild(emailNode);
Text emailtextNode=doc.createTextNode("simpson@hotmail.com");
emailNode.appendChild(emailtextNode);

Element root=doc.getDocumentElement();
Node firstChildNode=root.getFirstChild();
root.insertBefore(personNode,firstChildNode);


FileOutputStream outputstream=new FileOutputStream("C:\\examplebook1.xml");
TransformerFactory tfactory=TransformerFactory.newInstance();
StreamSource insource=new StreamSource(document);
StreamResult sresult=new StreamResult(outputstream);
Transformer transformer=tfactory.newTransformer();
transformer.transform(insource,sresult);

}

**************************************************************

Following is the xml file:

<?xml version = '1.0' encoding = 'UTF-8'?>
<folks>
<person>
<name>
Victor Van
<bold> Creator
</bold>
Frankenstien
</name>
<phone> 907564537</phone>
<email>
victor_van@hotmail.com
</email>
</person>
</folks>
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

First you parse an XML file into a Document.

Then you make some changes to the contents of that Document.

Then you transform the original XML file into a new XML file.

Naturally the changes you made to the Document are lost, as you completely ignored them. Read the code fragment I posted carefully and ask yourself why you made that change to it.
ahsan mir
Ranch Hand

Joined: Jul 17, 2006
Posts: 42
now i am really lost. after trying what you mentioned, I am having the following runtime error:

******************************
XML-22101: (Fatal Error) DOMSource node as this type not supported.
*****************************

This was generated after adding the following code :

DOMSource mdom=new DOMSource(doc);
transformer.transform(mdom,sresult);

Could you please reply with any code adjustments
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Seems to me that you have created something that isn't a valid XML document -- it contains more than one element at the top level. I could be wrong (I don't do much DOM programming because I hate the sort of code you have to write there, so I look for alternative solutions) but I am pretty sure that the "document element" is an imaginary element whose single child is the root element, in your case the "folks" element. If I read your code right, you are adding a sibling element before that.
ahsan mir
Ranch Hand

Joined: Jul 17, 2006
Posts: 42
hmm, I was using an example from the book: Java,XML and JAXP by A Griffiths. Here supposedly the new node(personNode) gets added as a child to the root element(folks).
You mentioned other ways to try this out, may i know how you would have proceeded .The XML document i have is very large with quite a complex schema.I have tried XMLBeans (only can read data)but cant find any useful documentation/examples on using its setter methods.JAXB wont compile the schema for some reason.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Unfortunately I would probably use DOM for this particular problem. Did you check to see what kind of element you inserted your new node into, and what its name was?
ahsan mir
Ranch Hand

Joined: Jul 17, 2006
Posts: 42
well this is confusing.After adding the following code:

***************************************************
NodeList n2=doc.getElementsByTagName("name");
int x=n2.getLength();
for(int g=0;g<=x-1;g++)
{
System.out.println(n2.item(g).getFirstChild().getNodeValue());
}

*********************************************************
I get the following output plus the earlier error/exception.Here the inserted node's value gets printed as well.Could it be something to do with the DOMSource class itself???
.............................................

Laany simpson
victor van

XML-22101: (Fatal Error) DOMSource node as this type not supported.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

That code doesn't do anything to test whether you have somehow created a document with more than one root element.
 
 
subject: making changes to an xml document...help needed!
 
Similar Threads
help regarding createing node in xml file
xml updations and deletions
xml parsing with dom
Null pointer exception probably due to synchronisation issues; problem in starting activity
Need help in replacing a node value