最近學(xué)習(xí)xml,把學(xué)習(xí)的代碼發(fā)上來 希望對新手有用
這是note.xml
<?xml version="1.0" encoding="gb2312" ?>
<notes>
<note date="2007-4-12">
<from>小紅</from>
<to>小林</to>
<message>周末一起去吃火鍋呀</message>
</note>
</notes>
這是dom解析xml代碼
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
class DomXMLTest
{
public static void main(String[] args)
{
try{
//(1)得到DOM解析器的工廠實例
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
//(2)從DOM工廠獲得DOM解析器
DocumentBuilder builder=factory.newDocumentBuilder();
File f=new File("note.xml");
//(3)把要解析的XML文檔轉(zhuǎn)化為輸入流,以便DOM解析器解析它
InputStream is=new FileInputStream(f);
//(4)解析XML文檔的輸入流,得到一個Document
Document doc=builder.parse(is);
//(5)得到XML文檔的根節(jié)點
Element root=doc.getDocumentElement();
//(6)得到節(jié)點的子節(jié)點
NodeList notes=root.getChildNodes();
for(int i=0;i<notes.getLength();i++)
{
Node note=notes.item(i);
if(note.getNodeType()==Node.ELEMENT_NODE)
{
//(7)取得節(jié)點的屬性值
String date =note.getAttributes().getNamedItem("date").getNodeValue();
System.out.println(date);
// (8)輪循子節(jié)點
for(Node node=note.getFirstChild();node!=null;node=node.getNextSibling())
{
if(node.getNodeType()==Node.ELEMENT_NODE)
{
if(node.getNodeName().equals("from"))
{
String from=node.getFirstChild().getNodeValue();
System.out.println(from);
}
if(node.getNodeName().equals("to"))
{
String to=node.getFirstChild().getNodeValue();
System.out.println(to);
}
if(node.getNodeName().equals("message"))
{
String message=node.getFirstChild().getNodeValue();
System.out.println(message);
}
}
}
}
}
}
catch(ParserConfigurationException e)
{
e.printStackTrace();
}
catch(SAXException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
還有 出現(xiàn) 下面的錯誤 是xml的格式不對 ,我就應(yīng)為在 <?xml 前面多個空格 就找了好幾天的錯誤
特別感謝那些幫我找問題的高手,用范偉的話說 謝謝啊
The processing instruction target matching "[xX][mM][lL]" is not allowed.