读书人

DOM解析xml的有关问题

发布时间: 2013-07-09 09:50:47 作者: rapoo

DOM解析xml的问题
xml代码
<?xml version="1.0"?>
<animals>
<animal>
<name>tiger</name>
<weight>500 pounds</weight>
<length>3 yard from nose to tail</length>
</animal>
<animal>
<name>rhino</name>
<weight>900 pounds</weight>
<length>9 yard from nose to tail</length>
</animal>
<animal>
<name>pp</name>
<weight>900sdfsdf pounds</weight>
<length>sdfsdfsdfsdfsdfs yard from nose to tail</length>
</animal>
</animals>
java代码
public class dom {

/**
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
// TODO Auto-generated method stub
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc = builder.parse(new File("d/animal.xml"));

/////////////////插入节点////////////////////////////////////////
Element animals= null;
Element animal = null;
Element name = null;
Element weight = null;
Element length = null;
NodeList list = doc.getElementsByTagName("animals");
animals = (Element)list.item(0);

animal = doc.createElement("animal");


name = doc.createElement("name");
name.appendChild(doc.createTextNode("nnnnnn"));
animal.appendChild(name);

weight = doc.createElement("weight");
weight.appendChild(doc.createTextNode("111111111111"));
animal.appendChild(weight);

length = doc.createElement("length");
length.appendChild(doc.createTextNode("123123"));
animal.appendChild(length);


animals.appendChild(animal);
////////////////////////////////////////////
NodeList n1 = doc.getElementsByTagName("animal");
for(int i=0; i<n1.getLength(); i++) {


Element node = (Element) n1.item(i);
System.out.print("name:");
System.out.println(node.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
System.out.print("weight:");
System.out.println(node.getElementsByTagName("weight").item(0).getFirstChild().getNodeValue());
System.out.print("length:");
System.out.println(node.getElementsByTagName("length").item(0).getFirstChild().getNodeValue());
System.out.println("=====================================");

}
////////////////////////////////////////////////

////////////删除节点/////////////////////////////////////////////////////
/* NodeList root = doc.getElementsByTagName("animals");

Element nodeq = (Element) root.item(0);
nodeq.removeChild(nodeq.getChildNodes().item(3));*/
/////////////////////////////////////////////////////////////////////
///////////////////修改节点//////////////////////////////////////////////////

}

}
哪位大哥教写下删除节点 和 修改节点的java代码
DOM XML Java
[解决办法]

public final class TestXMLCRUD {

public static void main(String[] args) {
new TestXMLCRUD();
}

public TestXMLCRUD() {

try {

Document doc = createNewDocument();
setRootNode(doc, "ThisIsTheRootNode");

Element child = addElement(doc, "ThisIsAChildNodeOfRoot");
addElement(doc, child, "ThisIsAChildNode", "I Have text!");
System.out.println(save(doc));

} catch (TransformerConfigurationException ex) {
ex.printStackTrace();


} catch (IOException ex) {
ex.printStackTrace();
} catch (TransformerException ex) {
ex.printStackTrace();
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
} catch (DOMException ex) {
ex.printStackTrace();
}

}
private DocumentBuilder builder;

public Node getRootNode(Document xmlDoc) {

Node nRoot = null;

if (xmlDoc != null) {

nRoot = xmlDoc.getDocumentElement();

}

return nRoot;

}

public Document createNewDocument() throws ParserConfigurationException {

Document doc = getDocumentBuilder().newDocument();
Element root = doc.createElement("root");
doc.adoptNode(root);
doc.appendChild(root);

return doc;

}

public Element setRootNode(Document xmlDoc, String name) {

removeNode(getRootNode(xmlDoc));
Element root = xmlDoc.createElement(name);
xmlDoc.adoptNode(root);
xmlDoc.appendChild(root);

return root;


}

public Document loadDocument(InputStream is) throws ParserConfigurationException, SAXException, IOException {

return getDocumentBuilder().parse(is);

}

public Document loadDocument(File file) throws ParserConfigurationException, SAXException, IOException {

return getDocumentBuilder().parse(file);

}

public Document loadDocumentFromString(String xml) throws ParserConfigurationException, SAXException, IOException {

Document doc = null;

ByteArrayInputStream bais = null;

//StringReader sr = null;
//InputSource is = null;


try {

bais = new ByteArrayInputStream(xml.getBytes());

doc = loadDocument(bais);

} finally {

// try { sr.close(); } catch (Exception e) { }
try {
bais.close();
} catch (Exception e) {
}

}

return doc;

}

protected DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {

if (builder == null) {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false); // You might want to change this...
builder = factory.newDocumentBuilder();

}

return builder;

}

public Element addElement(Document xmlDoc, String name) {

Element child = xmlDoc.createElement(name);
getRootNode(xmlDoc).appendChild(child);

return child;

}

public Node addElement(Document xmlDoc, Node node, String name) {

Node child = xmlDoc.createElement(name);
node.appendChild(child);

return child;

}

public Node addElement(Document xmlDoc, Node node, String name, String text) {

Node child = addElement(xmlDoc, node, name);
child.setTextContent(text);

return child;

}

public void removeNode(Node parentNode) {

if (parentNode != null) {

while (parentNode.hasChildNodes()) {

removeNode(parentNode.getFirstChild());

}

Node parent = parentNode.getParentNode();


if (parent != null) {

parent.removeChild(parentNode);

NodeList childNodes = parent.getChildNodes();
if (childNodes.getLength() > 0) {

List<Node> lstTextNodes = new ArrayList<Node>(childNodes.getLength());
for (int index = 0; index < childNodes.getLength(); index++) {

Node childNode = childNodes.item(index);
if (childNode.getNodeType() == Node.TEXT_NODE) {

lstTextNodes.add(childNode);

}

}

for (Node node : lstTextNodes) {

removeNode(node);

}

}

}

}

}

public void save(Document xmlDoc, File fFile) throws TransformerConfigurationException, TransformerException, IOException {

FileOutputStream fos = null;

try {

fos = new FileOutputStream(fFile);
save(xmlDoc, fos);

fos.flush();

} finally {

try {
fos.close();
} catch (Exception e) {
}

}

}



public void save(Document xmlDoc, OutputStream os) throws TransformerConfigurationException, TransformerException, IOException {

OutputStreamWriter osw = null;

try {

osw = new OutputStreamWriter(os);
save(xmlDoc, osw);
osw.flush();

} finally {

try {
osw.close();
} catch (Exception exp) {
}

}

}

public String save(Document xmlDoc) throws TransformerConfigurationException, IOException, TransformerException {

String sValue = null;

ByteArrayOutputStream baos = null;

try {

baos = new ByteArrayOutputStream();
save(xmlDoc, baos);
baos.flush();
sValue = new String(baos.toByteArray());

} finally {

try {
baos.close();
} catch (Exception exp) {
}

}

return sValue;

}

public void save(Document xmlDoc, Writer os) throws TransformerConfigurationException, TransformerException {

Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.METHOD, "xml");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

DOMSource domSource = new DOMSource(xmlDoc);
StreamResult sr = new StreamResult(os);
tf.transform(domSource, sr);

}
}

读书人网 >Java相关

热点推荐