xml格式化,xml格式化代码

灰太狼 2024-04-03 13:53 263阅读 0赞

  import org.apache.xml.serialize.OutputFormat;

  import org.apache.xml.serialize.OutputFormat;

  import org.apache.xml.serialize.XMLSerializer;

  import org.w3c.dom.Document;

  import org.xml.sax.InputSource;

  import org.xml.sax.SAXException;

  import javax.xml.parsers.DocumentBuilder;

  import javax.xml.parsers.DocumentBuilderFactory;

  import javax.xml.parsers.ParserConfigurationException;

  import java.io.IOException;

  import java.io.StringReader;

  import java.io.StringWriter;

  import java.io.Writer;

  public class XmlFormatter {

  public String format(String unformattedXml) {

  try {

  final Document document=parseXmlFile(unformattedXml);

  OutputFormat format=new OutputFormat(document);

  format.setLineWidth(65);

  format.setIndenting(true);

  format.setIndent(2);

  Writer out=new StringWriter();

  XMLSerializer serializer=new XMLSerializer(out, format);

  serializer.serialize(document);

  return out.toString();

  } catch (IOException e) {

  throw new RuntimeException(e);

  }

  }

  private Document parseXmlFile(String in) {

  try {

  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

  DocumentBuilder db=dbf.newDocumentBuilder();

  InputSource is=new InputSource(new StringReader(in));

  return db.parse(is);

  } catch (ParserConfigurationException e) {

  throw new RuntimeException(e);

  } catch (SAXException e) {

  throw new RuntimeException(e);

  } catch (IOException e) {

  throw new RuntimeException(e);

  }

  }

  public static void main(String[] args) throws Exception{

  String s=” 35 atgtca 10 90 10 admin 111111 P 2 “;//隆鯉塀晒念議xml

  System.out.println(new XmlFormatter().format(s));

  }

  }

发表评论

表情:
评论列表 (有 0 条评论,263人围观)

还没有评论,来说两句吧...

相关阅读

    相关 xml格式化工具

      xml格式化工具提供了最简单的代码格式化功能,可以让编辑的代码得到优化,解决一些文本格式错误以及代码失效的问题,让你可以在编辑xml的时候优化源代码。xml格式化工具使用非

    相关 java xml格式化

      构建xml文档   所以我不能使用像XStream这样的XML序列化器:它将XML格式基于Java类。同样,像JAXB这样的Java XML绑定技术也不行,因为它从XML