欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java解析xml,给元素添加属性,javaxml,package cn.o

来源: javaer 分享于  点击 43398 次 点评:82

java解析xml,给元素添加属性,javaxml,package cn.o


package cn.outofmemory.snippets.core;import java.io.File;import java.io.FileInputStream;import java.io.StringWriter;import java.io.Writer;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;public class AddAttributeInDOMElement {    public static void main(String[] args) throws Exception {        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();        dbf.setValidating(false);        DocumentBuilder db = dbf.newDocumentBuilder();        Document doc = db.parse(new FileInputStream(new File("in.xml")));        Element element = (Element) doc.getElementsByTagName("channel").item(0);        // Adds a new attribute. If an attribute with that name is already present         // in the element, its value is changed to be that of the value parameter        element.setAttribute("newattr", "attrvalue");        prettyPrint(doc);        // whether an attribute with a given name is specified on this element or has a default value        boolean hasAttribute = element.hasAttribute("newattr");        System.out.println("Attribute Added: " + hasAttribute);    }    public static final void prettyPrint(Document xml) throws Exception {        Transformer tf = TransformerFactory.newInstance().newTransformer();        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");        tf.setOutputProperty(OutputKeys.INDENT, "yes");        Writer out = new StringWriter();        tf.transform(new DOMSource(xml), new StreamResult(out));        System.out.println(out.toString());    }}

Input:

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">    <channel>        <title>Java Tutorials and Examples</title>        <item>            <title><![CDATA[Java Tutorials]]></title>            <link>http://byrx.net/</link>        </item>        <item>            <title><![CDATA[Java Examples]]></title>            <link>http://byrx.net/</link>        </item>    </channel></rss>

输出:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss version="2.0">    <channel newattr="attrvalue">        <title>Java Tutorials and Examples</title>        <item>            <title><![CDATA[Java Tutorials]]></title>            <link>http://byrx.net/</link>        </item>        <item>            <title><![CDATA[Java Examples]]></title>            <link>http://byrx.net/</link>        </item>    </channel></rss>Attribute Added: true
相关栏目:

用户点评