Created
May 20, 2013 16:57
-
-
Save fumokmm/5613568 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import javax.xml.parsers.*; | |
import javax.xml.transform.*; | |
import javax.xml.transform.dom.*; | |
import javax.xml.transform.stream.*; | |
import org.w3c.dom.*; | |
public class XmlTest { | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) throws Exception { | |
// ファクトリ生成 | |
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); | |
// ビルダー生成 | |
DocumentBuilder builder = factory.newDocumentBuilder(); | |
// ファイル読み込み | |
File f = new File("test.xml"); | |
Document doc = builder.parse(f); | |
// ルート要素の取得 | |
Element root = doc.getDocumentElement(); | |
System.out.println(root.getTagName()); | |
// 子要素の取得 | |
NodeList children = root.getChildNodes(); | |
for (int i = 0; i < children.getLength(); i++) { | |
Node child = children.item(i); | |
if (child instanceof Element) { | |
Element childElement = (Element) child; | |
System.out.println(childElement.getTagName()); | |
System.out.println(childElement.getAttribute("xxx")); | |
} | |
} | |
// ここから出力のソース | |
TransformerFactory tfFac = TransformerFactory.newInstance(); | |
Transformer tf = tfFac.newTransformer(); | |
DOMSource source = new DOMSource(doc); | |
File outFile = new File("test_out.xml"); | |
FileOutputStream fos = new FileOutputStream(outFile); | |
StreamResult result = new StreamResult(fos); | |
tf.transform(source, result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment