แสดงบทความที่มีป้ายกำกับ Xml แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ Xml แสดงบทความทั้งหมด

29 ก.ย. 2554

Java create xml and read

Java create xml and read

package ball.Xml;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

public class CreateXml {
 private String output;
 public static void main(String[] args ) throws TransformerConfigurationException, IOException{
  new CreateXml();
 }
 public CreateXml() throws TransformerConfigurationException, IOException{
  System.out.println("Create Element");
  output = "output.xml";
  CreateElement();
  ReadXml();
 }
 private void CreateElement() {
  try {
            /////////////////////////////
            //Creating an empty XML Document
            //We need a Document
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            ////////////////////////
            //Creating the XML tree

            //create the root element and add it to the document
            Element root = doc.createElement("root");
            doc.appendChild(root);

            //create a comment and put it in the root element
            Comment comment = doc.createComment("Just a thought");
            root.appendChild(comment);

            //create child element, add an attribute, and add to root
            Element child = doc.createElement("child");
            root = addAttribute(root,child,"a","b");
            root = addAttribute(root,child,"x","a");
            root = addAttribute(root,child,"x","a");

            //add a text element to the child
            Text text = doc.createTextNode("Filler, ... I could have had a foo!");
            child.appendChild(text);
            Element info = doc.createElement("Information");
            root.appendChild(info);
            root = addAttribute(root, info, "Name", "Wongsakorn");
            info.appendChild(doc.createTextNode("Hello"));
            root = addAttribute(root, info, "SureName", "Kongosod");
            /////////////////
            //Output the XML

            //set up a transformer
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult result = new StreamResult(new File(output));
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);

        } catch (Exception e) {
            System.out.println(e);
        }
 }
 private void ReadXml() throws TransformerConfigurationException, IOException {
        //print xml
        System.out.println("Here's the xml:\n");
        InputStream ins = new FileInputStream(new File(output));
        DataInputStream data = new DataInputStream(ins);
        BufferedReader reader = new BufferedReader(new InputStreamReader(data));
        String strLine = "";
        while ((strLine = reader.readLine())!=null) {
   System.out.println(strLine);
  }
 }
 private Element addAttribute(Element root, Element child, String name,String value) {
  child.setAttribute(name, value);
        root.appendChild(child);
  return root;
 }
}

output:

<root>
<!--Just a thought-->
<child a="b" x="a">Filler, ... I could have had a foo!</child>
<Information Name="Wongsakorn" SureName="Kongosod">Hello</Information>
</root>

27 ก.ย. 2554

ReadXml

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLReader {
private String out = "";
private HashMap<Node, String> checkEle;
private HashMap<String, Node> mapRoot;
public static void main(String argv[]) throws ParserConfigurationException,
SAXException, IOException {
new XMLReader();
}

public XMLReader() throws ParserConfigurationException, SAXException,
IOException {
DocumentBuilderFactory docBuild = DocumentBuilderFactory.newInstance();
docBuild.setNamespaceAware(false);
docBuild.setIgnoringComments(true);
docBuild.setIgnoringElementContentWhitespace(true);
DocumentBuilder build = docBuild.newDocumentBuilder();
Document doc = build.parse(new File("input.xml"));
Element root = doc.getDocumentElement();
parser(root);
}

public void parser(Element element) {
System.out.println(element.getNodeName());
NodeList list1 = element.getChildNodes();
checkEle = new HashMap<Node, String>();
mapRoot = new HashMap<String, Node>();
parserChildNode(list1,0);
System.out.println(out);
}
public void parserChildNode(NodeList list,int indexChild) {
String tab = "|  |";
for (int i = 0; i < indexChild; i++) {
tab+="|  |";
}
if (list != null) {
for (int i = 0; i < list.getLength(); i++) {
if (!list.item(i).getNodeName().equals("#text")) {
if(mapRoot.get(list.item(i))!=null){
tab = checkEle.get(mapRoot.get(list.item(i).getNodeName()));
}
NamedNodeMap attribute = list.item(i).getAttributes();
if(attribute!=null && attribute.getLength()>0){
String text = "";
if(list.item(i).hasChildNodes())
text = list.item(i).getFirstChild().getTextContent();
if(checkEle.get(list.item(i)) != null)
out += checkEle.get(list.item(i))+"<"+list.item(i).getNodeName()+"> "+text;
else{
out += tab+"<"+list.item(i).getNodeName()+">";
checkEle.put(list.item(i), tab);
}
}
else{
String text = "";
if(list.item(i).hasChildNodes())
text = list.item(i).getFirstChild().getTextContent();
out += tab+"<"+list.item(i).getNodeName()+"> "+text+"\n";
}
if(attribute!=null && attribute.getLength()>0){
for (int j = 0; j < attribute.getLength(); j++) {
out +=attribute.item(j).getNodeName()+"="+attribute.item(j).getNodeValue();
}
out+="\n";
}
if(list.item(i).getChildNodes()!=null){
if(mapRoot.get(list.item(i).getParentNode())== null){
mapRoot.put(list.item(i).getParentNode().getNodeName(),list.item(1));
parserChildNode(list.item(i).getChildNodes(),indexChild++);
}
}
}

}
}
}
}

19 ก.ค. 2554

Xml to Html

แปลง  xml เป็น html

ไฟล์ hello.xsl

<xsl:stylesheet version = '1.0'
     xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match="h1">
       <h1>
      <center>
     <xsl:value-of select="."/>
               </center>
            </h1>
</xsl:template>
<xsl:template match="bold">
     <table align="center" border="1">
       <tr>
    <xsl:for-each select=".">
       <td>
        <xsl:value-of select="."/>
       </td>
    </xsl:for-each>
            </tr>
     </table>
</xsl:template>
<xsl:template match="red">
<table align="center" border="1">
      <tr>
   <td>
     <p style="color:red">
    <xsl:value-of select="."/>
     </p>
   </td>
        </tr>  
     </table>
</xsl:template>
<xsl:template match="italic">
<table align="center" border="1">
      <tr>
   <td>
    <p>
     <xsl:value-of select="."/>
    </p>
            </td>
        </tr>
          
     </table>
</xsl:template>
</xsl:stylesheet> 

hello.xml


<?xml version="1.0"?>

<source>

<h1>TEST XSLT FOR CREATE WEB SITE BY WONGSAKORN</h1>

<bold>Hello1, world.</bold>

<bold>Hello2, world.</bold>

<bold>Hello3, world.</bold>

<bold>Hello4, world.</bold>

<bold>Hello5, world.</bold>

<red>I am </red>

<italic>fine.</italic>

</source>


SimpleTransformHtml.java 

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JOptionPane;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class SimpleTransformHtml
{
 public static void main(String[] args)
    throws TransformerException, TransformerConfigurationException, 
           FileNotFoundException, IOException{  
 TransformerFactory tFactory = TransformerFactory.newInstance();
 String sourceFile = "hello";
 String html = ".html";
 Transformer transformer = tFactory.newTransformer(new StreamSource(sourceFile+xsl));
 transformer.transform(new StreamSource(sourceFile+xml), new StreamResult(new FileOutputStream(sourceFile+html)));
 System.out.println("************* The result is in "+sourceFile+html+" *************");
 Runtime.getRuntime().exec
   ("rundll32 SHELL32.DLL,ShellExec_RunDLL " + sourceFile+html);
  }
}


จะได้ตามด้านล้างนี้

TEST XSLT FOR CREATE WEB SITE BY WONGSAKORN

Hello1, world.
Hello2, world.
Hello3, world.
Hello4, world.
Hello5, world.
I am
fine.

Java Read XML

Java Read XML

try {     
            StringBuffer strFile = new StringBuffer();
       DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
       DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
       Document doc = docBuilder.parse (new File(inputfile));
       doc.getDocumentElement ().normalize ();
       NodeList listOfDoc = doc.getElementsByTagName("writer");
       for(int s=0; s<listOfDoc.getLength() ; s++){
        Element firstDocNode = (Element) listOfDoc.item(s);
        String name= firstDocNode.getAttribute("Name");
        System.out.println(name);
       }
   }catch (Throwable t) {
    t.printStackTrace ();
   }


input.xml

<?xml version="1.0"?>
<Document>
 <Title>
  <writer Name="A"/>
  <writer Name="B"/>
  <writer Name="C"/>
  <writer Name="D"/>
  <writer Name="E"/>
  <writer Name="F"/>
  <writer Name="G"/>
  <writer Name="H"/>
 </Title>
</Document>