Document Object To XML String


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

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;

/**
 *
 * Desc:<br>
 * 使用org.w3c.dom分析xml文档.<br>
 * 把Document Object转成xml字符串.<br>
 * Version:V1.0
 * Create Date:2006-11-20
 * Aauthor                Date                     Detail
 * Chuncheng Cao        2006-11-20                    Create                                                
 *
 *
 */

public class TestDocument2String {
 
 public TestDocument2String() {

 }
 /**
  * testing
  * @param args
  */
 public static void main(String[] args) {
  TestDocument2String d2s = new TestDocument2String();
  Document doc = d2s.getDocumentFromString(d2s.getTestXML());
  String xml = d2s.getStringFromDocument(doc);
  System.out.println("xml := ");
  System.out.println(xml);
  
  TestDocument2String d2s1 = new TestDocument2String();
  Document doc1 = d2s1.getDocumentFromFile("D:" + File.separator + "eclipselomboz" + File.separator + "workspace" + File.separator + "test" + File.separator + "xml" + File.separator + "doc.xml");
  String xml1 = d2s1.getStringFromDocument(doc1);
  System.out.println("xml := ");
  System.out.println(xml1);
  
  
 }
 /**
  * get xml string for document object
  * @param doc
  * @return xml string
  */
 public  String getStringFromDocument(Document doc){
  StringBuffer sb = new StringBuffer("");
  Element root = doc.getDocumentElement();
  doDoc2String(root,sb,"");
  return sb.toString();
 }
 /**
  * 递归分析节点,组成xml字符串
  * @param ele
  * @param sb
  * @param index
  */
 public void doDoc2String(Element ele,StringBuffer sb,String index){
  if(ele == null){
   return;
  }
  index = index + "    ";
  String eleName = ele.getNodeName()== null?"":ele.getNodeName();
  String eleValue = ele.getNodeValue()== null?"":ele.getNodeValue();
  NamedNodeMap nodeMap = ele.getAttributes();
  if(nodeMap.getLength() > 0){
   sb.append(index + "<" +eleName);
   for(int i = 0; i < nodeMap.getLength(); i ++){
    Node node = (Node)nodeMap.item(i);
    String nodeName = node.getNodeName()== null?"":node.getNodeName().trim();
    String nodeValue = node.getNodeValue()== null?"":node.getNodeValue().trim();
    sb.append("  " + nodeName + "=/"" + nodeValue + "/"");
   }
   sb.append(">");
  }else{
   sb.append(index + "<" +eleName + ">");
  }
  
  NodeList list = ele.getChildNodes();
  for(int n = 0; n < list.getLength(); n ++){
   Node child = list.item(n);
   if(child instanceof Element){
    sb.append("/n");
    doDoc2String((Element)child,sb,index);
   }else{
    eleValue = child.getNodeValue() == null?"" : child.getNodeValue().trim() ;
   }
  }
  
  if(eleValue.equals("")){
   sb.append(eleValue);
   sb.append(index + "</"+eleName+"> /n");
  }else{
   sb.append(eleValue);
   sb.append("</"+eleName+"> /n");
  }
  
 }
 /**
  * 加载xml文件,返回Docuemnt对象
  * @param fileName
  * @return
  */
 public Document getDocumentFromFile(String fileName){
  File f = new File(fileName);
  FileInputStream inStream = null;
  try {
   inStream = new FileInputStream(f);
  } catch (FileNotFoundException fe) {
   // TODO 自动生成 catch 块
   System.out.println("Fail to create file input stream from string:" + fe.getMessage());
  }
  Document doc = null;
  try {
   DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance();
   DocumentBuilder docBuilder = (DocumentBuilder) docBF
     .newDocumentBuilder();
   doc = docBuilder.parse(inStream);
  } catch (Exception e) {
   System.out.println("readDOM throw err: " + e.getClass().getName() + e.getMessage());
  } finally {
   try {
    if (inStream != null)
     inStream.close();
   } catch (Exception e) {
    System.out.println("Fail to close input stream: " + e.getMessage());
   }
   return doc;
  }
 }
 /**
  * 加载xml字符串,返回Document对象
  * @param xml
  * @return
  */
 public  Document getDocumentFromString(String xml) {

  ByteArrayInputStream inStream = null;
  try {
   inStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
  } catch (UnsupportedEncodingException ue) {
   // TODO 自动生成 catch 块
   System.out.println("Fail to create byte input stream from string:" + ue.getMessage());
  }
  Document doc = null;
  try {
   DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance();
   DocumentBuilder docBuilder = (DocumentBuilder) docBF
     .newDocumentBuilder();
   doc = docBuilder.parse(inStream);
  } catch (Exception e) {
   System.out.println("readDOM throw err: " + e.getClass().getName() + e.getMessage());
  } finally {
   try {
    if (inStream != null)
     inStream.close();
   } catch (Exception e) {
    System.out.println("Fail to close input stream: " + e.getMessage());
   }
   return doc;
  }
 }
 /**
  * 测试xml字符串
  * @return
  */
 public  String getTestXML() {
  String xml = "";
  xml = "<?xml version=/"1.0/" encoding=/"UTF-8/"?>"
    + "<TradeDeclaration issuerId=/"XXXXXX/""
    + " issuerName=/"XXXXXX/""
    + " language=/"S/""
    + " messageReference=/"6B449IXO1J000R/""
    + " senderRoutingAddress=/"GT/""
    + " submissionMode=/"A/""
    + " xmlns=/"http://www.gets.gov.hk/tdec/""
    + " xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/""
    + " xsi:schemaLocation=/"http://www.gets.gov.hk/tdec TdecTradeDeclaration.xsd/">"
    +

    "<MessageType>TDLD01</MessageType>"
    + "<MessageName>HAV</MessageName>"
    + "<MessageFunction>9</MessageFunction>"
    +

    "<DeclarantInfo>"
    + "<DeclarantName declarantType=/"IM/">TEST</DeclarantName>"
    + "<DeclarantBrIdNo type=/"XA/">44444444-444</DeclarantBrIdNo>"
    + "<DeclarationDate>2006-09-14</DeclarationDate>"
    + "<DeclarationTextCode>011</DeclarationTextCode>"
    + "<DeclarantAddress>MLC BUILDING</DeclarantAddress>"
    + "<DeclarantAddress>HONG KONG</DeclarantAddress>"
    + "</DeclarantInfo>"
    +

    "<ValueAndPackageInfo>"
    + "<TotalCifFobValue>10000.00</TotalCifFobValue>"
    + "<CifFobValueType>HCV</CifFobValueType>"
    + "<TotalNoOfPackages>1</TotalNoOfPackages>"
    + "</ValueAndPackageInfo>"
    +

    "<ShipmentInfo>"
    + "<DepartureArrivalDate>2006-09-14</DepartureArrivalDate>"
    + "<TransportMode>1</TransportMode>"
    + "<TransportId>1111</TransportId>"
    + "<TransportRefNo>11111</TransportRefNo>"
    + "</ShipmentInfo>"
    +

    "<PortAndLocationInfo>"
    + "<PortOfLoadingDischargeName>1111</PortOfLoadingDischargeName>"
    + "<PortType>9</PortType>"
    + "<ExportingDestinationCountry countryType=/"35/">AF</ExportingDestinationCountry>"
    + "</PortAndLocationInfo>" +

    "<AirWaybillBillOfLadingInfo>"
    + "<ConsolidationItemNo>1</ConsolidationItemNo>"
    + "<MasterAirWaybillNo>111111</MasterAirWaybillNo>"
    + "<ConsolidationIndicator>N</ConsolidationIndicator>"
    + "<HouseAirWaybillNo>NA</HouseAirWaybillNo>" +

    "<LineItemDetails>" + "<LineItemNo>1</LineItemNo>"
    + "<NoOfPackages>1</NoOfPackages>"
    + "<TypeOfPackage>9F</TypeOfPackage>"
    + "<Quantity>1.00</Quantity>"
    + "<UnitOfQuantity>KGM</UnitOfQuantity>"
    + "<ItemCifFobValue>10000.00</ItemCifFobValue>"
    + "<OriginCountry>AM</OriginCountry>"
    + "<ContainerNo>1111111</ContainerNo>"
    + "<HsCode>28433010</HsCode>"
    + "<DescriptionOfCommodity>111111</DescriptionOfCommodity>"
    + "<ShippingMark>111111</ShippingMark>" + "</LineItemDetails>" +

    "</AirWaybillBillOfLadingInfo>" + "</TradeDeclaration>";
  return xml;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值