Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 1 of 1

Thread: XML DOM Parser problem

  1. #1
    Junior Member
    Join Date
    Apr 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default XML DOM Parser problem

    I have written the following java code for an XML Parser :
    import org.w3c.dom.*;
    import javax.xml.parsers.*;
    import java.io.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
     
    public class XMLParser
    {
    	int i, j;
    	private final static String xmlFileName = "/home/kanishk/Desktop/SE/mini proj/sample.xml";
    	public void XMLSearch()
    	{
    		try{
    		System.out.println("sapsap");
    		File file = new File(xmlFileName);
    		int flag = 0;
    		if (file.exists())
    		{
    			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    			DocumentBuilder parser = factory.newDocumentBuilder();
    			Document doc = parser.parse(xmlFileName);
    			BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
          			System.out.print("Enter search data: ");
          			String str = bf.readLine();
          			NodeList nl = doc.getElementsByTagName("*");
          			for(i=0;i<nl.getLength();i++)
          			{
          				if(nl.item(i).hasChildNodes())
          				{
          					if(nl.item(i).hasAttributes())
          					{
          						NamedNodeMap nnm = nl.item(i).getAttributes();
          						for(j=0;j<nnm.getLength();j++)
          						{
          							Attr a = (Attr)nnm.item(j);
          							if(str.equals(a.getValue()))
          							{
          								System.out.println("Search Data found");
          								flag = 1;
          							}
          						}
          					}
          					Node ch;
          					for(ch=nl.item(i).getFirstChild();ch!=null;ch=ch.getNextSibling())
          					{
          						if(ch.getNodeType()==Node.TEXT_NODE || ch.getNodeType()==Node.ATTRIBUTE_NODE)
          						{
          							if(ch.getNodeType()==Node.TEXT_NODE)
          							{
          								if(str.equals(ch.getNodeValue()))
          								{
          									System.out.println("Search Data found");
          									flag = 1;
          								}
          							}
          						}
          					}
          				}
          			}
          			if(flag==0)
          				System.out.println("Data Not Found");
          		}
          		else
          			System.out.println("File doesnt exist");
          		}
          		catch(Exception e){
          		System.out.println(e);}
          	}
          	public void XMLModify(int k)
          	{
          		try{
          		File file = new File(xmlFileName);
          		if (file.exists())
    		{
    			if(k==1)
    			{
    				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    				DocumentBuilder parser = factory.newDocumentBuilder();
    				Document doc = parser.parse(xmlFileName);
    				BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Enter parent node: ");
          				String str = bf.readLine();
          				BufferedReader bf1 = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Enter element name: ");
          				String str1 = bf1.readLine();
          				bf1 = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Give an element value(yes or no)?: ");
          				String str2 = bf1.readLine();
          				Node n1 = doc.createElement(str1);
          				NodeList nl = doc.getElementsByTagName(str);
          				for(j=0;j<nl.getLength();j++)
          				{
          					nl.item(j).appendChild(n1);
          					if(str2.equals("yes"))
          					{
          						bf1 = new BufferedReader(new InputStreamReader(System.in));
          						System.out.println("Enter element value: ");
          						String str3 = bf1.readLine();
          						Text txt = doc.createTextNode(str3);
          						n1.appendChild(txt);
          					}
          				}
          				storedata(doc);
          			}
          			if(k==2)
          			{
          				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    				DocumentBuilder parser = factory.newDocumentBuilder();
    				Document doc = parser.parse(xmlFileName);
          				BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Enter attribute node: ");
          				String str = bf.readLine();
          				BufferedReader bf2 = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Enter attribute value: ");
          				String str2 = bf2.readLine();
          				BufferedReader bf1 = new BufferedReader(new InputStreamReader(System.in));
          				System.out.print("Enter element name to which attribute should be added: ");
          				String str1 = bf1.readLine();
          				NodeList nl = doc.getElementsByTagName(str1);
          				for(j=0;j<nl.getLength();j++)
          				{
          					Element e = (Element)nl.item(j);
          					e.setAttribute(str,str2);
          				}
          				storedata(doc);
          			}
          			if(k==3)
          			{
          				Node n;
          				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    				DocumentBuilder parser = factory.newDocumentBuilder();
    				Document doc = parser.parse(xmlFileName);
          				BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Enter element to be replaced: ");
          				String str = bf.readLine();
          				BufferedReader bf1 = new BufferedReader(new InputStreamReader(System.in));
          				System.out.print("Enter new element: ");
          				String str1 = bf1.readLine();
          				bf1 = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Give an element value(yes or no)?: ");
          				String str2 = bf1.readLine();
          				n = doc.createElement(str1);
          				//Element e = doc.createElement(str);
          				NodeList nl = doc.getElementsByTagName(str);
          				for(j=0;j<nl.getLength();j++)
          				{
          					Node n1 = nl.item(j).getParentNode();
          					n1.removeChild(nl.item(j));
          					Node n2 = n1.appendChild(n);
          					if(str2.equals("yes"))
          					{
          						bf1 = new BufferedReader(new InputStreamReader(System.in));
          						System.out.println("Enter element value: ");
          						String str3 = bf1.readLine();
          						Text txt = doc.createTextNode(str3);
          						n2.appendChild(txt);
          					}
     
          				}
          				storedata(doc);
          			}
          			if(k==4)
          			{
          				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    				DocumentBuilder parser = factory.newDocumentBuilder();
    				Document doc = parser.parse(xmlFileName);
          				BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Enter attribute to be replaced: ");
          				String str = bf.readLine();
          				BufferedReader bf1 = new BufferedReader(new InputStreamReader(System.in));
          				System.out.print("Enter new attribute: ");
          				String str1 = bf1.readLine();
          				BufferedReader bf2 = new BufferedReader(new InputStreamReader(System.in));
          				System.out.print("Enter new attribute value: ");
          				String str2 = bf2.readLine();
          				NodeList nl = doc.getElementsByTagName("*");
          				for(j=0;j<nl.getLength();j++)
          				{
          					Element e = (Element)nl.item(j);
          					if(e.hasAttribute(str))
          					{
          						e.removeAttribute(str);
          						e.setAttribute(str1,str2);
          					}
          				}
          				storedata(doc);
          			}
          			if(k==5)
          			{
          				Node n;
          				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    				DocumentBuilder parser = factory.newDocumentBuilder();
    				Document doc = parser.parse(xmlFileName);
          				BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Enter element to be removed: ");
          				String str = bf.readLine();
          				NodeList nl = doc.getElementsByTagName(str);
          				for(j=0;j<nl.getLength();j++)
          				{
          					n = nl.item(j).getParentNode();
          					if(n!=null)
          						n.removeChild(nl.item(j));
          					else
          						System.out.println("Element not present in file");
          				}
          				storedata(doc);
          			}
          			if(k==6)
          			{
          				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    				DocumentBuilder parser = factory.newDocumentBuilder();
    				Document doc = parser.parse(xmlFileName);
          				BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Enter attribute to be removed: ");
          				String str = bf.readLine();
          				NodeList nl = doc.getElementsByTagName("*");
          				for(j=0;j<nl.getLength();j++)
          				{
          					Element e = (Element)nl.item(j);
          					if(e.hasAttribute(str))
          						e.removeAttribute(str);
          				}
          				storedata(doc);
          			}
          			if(k==7)
          			{
          				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    				DocumentBuilder parser = factory.newDocumentBuilder();
    				Document doc = parser.parse(xmlFileName);
          				BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Enter element whose value is to be updated: ");
          				String str = bf.readLine();
          				BufferedReader bf1 = new BufferedReader(new InputStreamReader(System.in));
          				System.out.print("Enter new value: ");
          				String str1 = bf1.readLine();
          				NodeList nl = doc.getElementsByTagName(str);
          				for(j=0;j<nl.getLength();j++)
          				{
          					if(nl.item(j).hasChildNodes())
          					{
          						NodeList nl1 = nl.item(j).getChildNodes();
          						for(i=0;i<nl1.getLength();i++)
          						{
          							if(nl1.item(i).getNodeType()==Node.TEXT_NODE);
          								nl1.item(i).setNodeValue(str1);
          						}
          					}
          					else
          						System.out.println("Element has no value");
          				}
          				storedata(doc);
          			}
          			if(k==8)
          			{
          				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    				DocumentBuilder parser = factory.newDocumentBuilder();
    				Document doc = parser.parse(xmlFileName);
          				BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
          				System.out.println("Enter attribute whose value is to be updated: ");
          				String str = bf.readLine();
          				BufferedReader bf1 = new BufferedReader(new InputStreamReader(System.in));
          				System.out.print("Enter new value: ");
          				String str1 = bf1.readLine();
          				NodeList nl = doc.getElementsByTagName("*");
          				for(j=0;j<nl.getLength();j++)
          				{
          					Element e = (Element)nl.item(j);
          					if(e.hasAttribute(str))
          					{
          						e.removeAttribute(str);
          						e.setAttribute(str,str1);
          					}
          				}
          				storedata(doc);
          			}
          		}
          		}
          		catch(Exception e){
          		System.out.println(e);}
          	}
          	private String nodevalue(Node n)
          	{
            	Node ch;
            	if(n!=null)
            	{
                 		if (n.hasChildNodes())
                 		{
                     		for(ch = n.getFirstChild();ch != null;ch = ch.getNextSibling())
                     		{
                         			if(ch.getNodeType() == Node.TEXT_NODE)
                             			return ch.getNodeValue();
                     		}
                 		}
             	}
             	return "";
         	}
          	public void XMLDisplay(Node n,int in)
          	{
          		File file = new File(xmlFileName);
          		if (file.exists())
          		{
            		String nn = n.getNodeName();
            		String str = nodevalue(n);
             		NamedNodeMap nnm = n.getAttributes();
             		System.out.println(indentspc(in) + "NodeName: " + nn + ", NodeValue: " + str);
             		if(nnm!=null)
             		{
             			for (int i = 0; i < nnm.getLength(); i++)
             			{
                    			Node n1 = nnm.item(i);
                  				System.out.println(indentspc(in + 2) + "AttributeName: " + n1.getNodeName() + ", attributeValue: " + n1.getNodeValue());
             			}
             		}
             		if(n.hasChildNodes())
             		{
             			NodeList ch = n.getChildNodes();
             			for (int i = 0; i < ch.getLength(); i++)
             			{
                 				Node ch1 = ch.item(i);
                 				if (ch1.getNodeType() == Node.ELEMENT_NODE)
                    		 		XMLDisplay(ch1,in + 2);
             			}
             		}
         		}
         		else
         			System.out.println("File doesnt exist");
         	}
         	private String indentspc(int in)
         	{
            	StringBuffer buffer = new StringBuffer();
             	for (int i = 0; i < in; i++)
                 		buffer.append(" ");
             	return buffer.toString();
         	}
         	private void storedata(Document doc)
         	{
         		try{
         		TransformerFactory trans = TransformerFactory.newInstance();
    		Transformer t = trans.newTransformer();
            	//StringWriter sw = new StringWriter();
            	//StreamResult r = new StreamResult(sw);
            	Node n = doc.getDocumentElement();
            	Source src = new DOMSource(n); 
            	Result dest = new StreamResult(System.out);
            	t.transform(src, dest);
            	/*DOMSource s = new DOMSource(doc);
            	t.transform(s,r);
            	String str = sw.toString();
            	OutputStream f;
    		byte buf[] = str.getBytes();
    		f = new FileOutputStream("connections.xml");
    		for(int i=0;i<buf.length;i++)
    	   		f.write(buf[i]);
    		f.close();
    		buf = null;*/
    		}
         		catch(Exception e){
          		System.out.println(e);}
    	}
         	public XMLParser()
         	{
         		try{
         		int x;
         		System.out.println("1. Search for data in XML file");
         		System.out.println("2. Modify data in XML file");
         		System.out.println("3. Display contents of XML file");
         		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
         		System.out.print("Choose one of the three possibilities(1, 2, 3) : ");
          		x = Integer.parseInt(bf.readLine());
          		if(x==1)
          			XMLSearch();
          		if(x==2)
          		{
          			int y;
          			System.out.println("1. Add Element");
          			System.out.println("2. Add Attribute");
          			System.out.println("3. Replace Element");
          			System.out.println("4. Replace Attribute");
          			System.out.println("5. Remove Element");
          			System.out.println("6. Remove Attribute");
          			System.out.println("7. Modify Element Value(If value present)");
          			System.out.println("8. Modify Attribute Value");
          			bf = new BufferedReader(new InputStreamReader(System.in));
          			System.out.println("Choose one of the given modification possibilities(1, 2, 3, 4, 5, 6, 7, 8) : ");
          			y = Integer.parseInt(bf.readLine());
          			switch(y)
          			{
          				case 1: XMLModify(1);break;
          				case 2: XMLModify(2);break;
          				case 3: XMLModify(3);break;
          				case 4: XMLModify(4);break;
          				case 5: XMLModify(5);break;
          				case 6: XMLModify(6);break;
          				case 7: XMLModify(7);break;
          				case 8: XMLModify(8);break;
          				default: System.out.println("Invalid Selection");break;
          			}
          		}
          		if(x==3)
          		{
          			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    			DocumentBuilder parser = factory.newDocumentBuilder();
    			Document doc = parser.parse(xmlFileName);
          			Node root = doc.getDocumentElement();
          			XMLDisplay(root,0);
          		}
          		}
          		catch(Exception e){
          		System.out.println("sasasaas123");
          		System.out.println(e);}
          	}
          	public static void main(String args[])
          	{
          		new XMLParser();
          	}
    }



    and iam parsing the following xml file :
    <?xml version="1.0"?>
    <catalog>
       <product description="Cardigan Sweater" product_image="cardigan.jpg">
          <catalog_item gender="Men's">
             <item_number>QWZ5671</item_number>
             <price>39.95</price>
             <size description="Medium">
                <color_swatch image="red_cardigan.jpg">Red</color_swatch>
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
             </size>
             <size description="Large">
                <color_swatch image="red_cardigan.jpg">Red</color_swatch>
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
             </size>
          </catalog_item>
          <catalog_item gender="Women's">
             <item_number>RRX9856</item_number>
             <price>42.50</price>
             <size description="Small">
                <color_swatch image="red_cardigan.jpg">Red</color_swatch>
                <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
             </size>
             <size description="Medium">
                <color_swatch image="red_cardigan.jpg">Red</color_swatch>
                <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
                <color_swatch image="black_cardigan.jpg">Black</color_swatch>
             </size>
             <size description="Large">
                <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
                <color_swatch image="black_cardigan.jpg">Black</color_swatch>
             </size>
             <size description="Extra Large">
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
                <color_swatch image="black_cardigan.jpg">Black</color_swatch>
             </size>
          </catalog_item>
       </product>
    </catalog>



    and when iam trying to modify the file(by adding the element color_divide with the value yes and parent node as color_swatch) iam getting the following file as output :
    <?xml version="1.0"?>
    <catalog>
       <product description="Cardigan Sweater" product_image="cardigan.jpg">
          <catalog_item gender="Men&apos;s">
             <item_number>QWZ5671</item_number>
             <price>39.95</price>
             <size description="Medium">
                <color_swatch image="red_cardigan.jpg">Red</color_swatch>
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
             </size>
             <size description="Large">
                <color_swatch image="red_cardigan.jpg">Red</color_swatch>
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
             </size>
          </catalog_item>
          <catalog_item gender="Women&apos;s">
             <item_number>RRX9856</item_number>
             <price>42.50</price>
             <size description="Small">
                <color_swatch image="red_cardigan.jpg">Red</color_swatch>
                <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
             </size>
             <size description="Medium">
                <color_swatch image="red_cardigan.jpg">Red</color_swatch>
                <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
                <color_swatch image="black_cardigan.jpg">Black</color_swatch>
             </size>
             <size description="Large">
                <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
                <color_swatch image="black_cardigan.jpg">Black</color_swatch>
             </size>
             <size description="Extra Large">
                <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
                <color_swatch image="black_cardigan.jpg">Black<color_divide>yesyesyesyesyesyesyesyesyesyesyesyesyesyes</color_divide></color_swatch>
             </size>
          </catalog_item>
       </product>
    </catalog>



    please help me out here.........i want color_divide to be added to each instance of color_swatch ........not only to the last one.........and with only 1 yes as the value each time.......
    Last edited by Json; April 13th, 2010 at 06:35 AM. Reason: Please use code tags.


Similar Threads

  1. recursive descent parser
    By gammaman in forum Algorithms & Recursion
    Replies: 4
    Last Post: March 21st, 2010, 03:50 AM
  2. Enforce DTD on DomParser - Make Parser fall over if error detected
    By toriacht in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 18th, 2010, 05:28 PM
  3. where can i get a Dom Parser jar ?
    By chinni in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: November 26th, 2009, 03:41 AM
  4. Infix to Prefix parser
    By r2ro_serolf in forum Java Theory & Questions
    Replies: 1
    Last Post: November 8th, 2009, 01:11 AM