10. september 2003 - 11:17
Der er
2 kommentarer og 1 løsning
Get Tag name from XML with Java
Hello! I try to (in a dynamic way) extrakt all tagnames from a xml-document. I also want to do this by only using sdk 1.4.1 (no extra packages is alowed). But I cant find any class that gives me the name of the tag. My code looks like: try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.parse( new File("test.xml") ); Element element = document.getDocumentElement(); System.out.println( element.getFirstChild().GETNAME() ); } catch (Exception ioe) { ioe.printStackTrace(); } The getFirstChild-method only gives my the Node. My test.xml looks like: <?xml version='1.0' encoding='utf-8'?> <show> <muppets> <mupp>Kermit</mupp> <mupp>Miss Piggy</mupp> </muppets> </show> And the names I want to get is for eg: show, muppets or mupp, not the value. Best regards Fredrik
Annonceindlæg fra HP
10. september 2003 - 11:36
#2
Eksempel: import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DomTest5 { private final static String XML_FILE = "C:\\domtest.xml"; public static void main(String[] args) { writeXml(XML_FILE); readXml(XML_FILE); } private static void writeXml(String filename) { try { PrintWriter pw = new PrintWriter(new FileOutputStream(filename)); pw.println("<?xml version='1.0' standalone='yes'?>"); pw.println("<list>"); pw.println("<a>1</a>"); pw.println("<bb>2</bb>"); pw.println("<ccc>3</ccc>"); pw.println("</list>"); pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } private static void readXml(String filename) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new File(filename)); NodeList list = doc.getDocumentElement().getChildNodes(); for(int i = 0; i < list.getLength(); i++) { if(list.item(i).getNodeType()==Node.ELEMENT_NODE) { System.out.println(list.item(i).getNodeName()); } } } catch (FactoryConfigurationError e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return; } } output: a bb ccc