/**
   * 格式化xml
   *
   * @param xml
   * @return
   */
  public static String formatXML(String xml) {

    SAXReader reader = null;
    XMLWriter writer = null;
    StringWriter stringWriter = null;
    try {
      reader = new SAXReader();
      org.dom4j.Document document = reader.read(new StringReader(xml));
      if (document != null) {
        stringWriter = new StringWriter();
        OutputFormat format = new OutputFormat("    ", false);
        format.setSuppressDeclaration(true);
        writer = new XMLWriter(stringWriter, format);
        writer.write(document);
        writer.flush();
      }
      return stringWriter.getBuffer().toString();
    } catch (Exception e) {
      LOG.error("格式化xml失败", e);
    } finally {
      try {
        writer.close();
        stringWriter.close();
      } catch (Exception e) {
        // ignore
      }
    }
    return xml;
  }
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static String executeXml(
      RepositoryFile file,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      IPentahoSession userSession)
      throws Exception {
    try {
      HttpSessionParameterProvider sessionParameters =
          new HttpSessionParameterProvider(userSession);
      HttpRequestParameterProvider requestParameters =
          new HttpRequestParameterProvider(httpServletRequest);
      Map parameterProviders = new HashMap();
      parameterProviders.put("request", requestParameters); // $NON-NLS-1$
      parameterProviders.put("session", sessionParameters); // $NON-NLS-1$
      List messages = new ArrayList();
      IParameterProvider requestParams = new HttpRequestParameterProvider(httpServletRequest);
      httpServletResponse.setContentType("text/xml"); // $NON-NLS-1$
      httpServletResponse.setCharacterEncoding(LocaleHelper.getSystemEncoding());
      boolean forcePrompt =
          "true"
              .equalsIgnoreCase(
                  requestParams.getStringParameter(
                      "prompt", "false")); // $NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$

      OutputStream contentStream = new ByteArrayOutputStream();
      SimpleOutputHandler outputHandler = new SimpleOutputHandler(contentStream, false);
      IRuntimeContext runtime = null;
      try {
        runtime =
            executeInternal(
                file,
                requestParams,
                httpServletRequest,
                outputHandler,
                parameterProviders,
                userSession,
                forcePrompt,
                messages);
        Document responseDoc =
            SoapHelper.createSoapResponseDocument(runtime, outputHandler, contentStream, messages);
        OutputFormat format = OutputFormat.createCompactFormat();
        format.setSuppressDeclaration(true);
        format.setEncoding("utf-8"); // $NON-NLS-1$
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(outputStream, format);
        writer.write(responseDoc);
        writer.flush();
        return outputStream.toString("utf-8"); // $NON-NLS-1$
      } finally {
        if (runtime != null) {
          runtime.dispose();
        }
      }
    } catch (Exception e) {
      logger.warn(
          Messages.getInstance().getString("XactionUtil.XML_OUTPUT_NOT_SUPPORTED")); // $NON-NLS-1$
      throw e;
    }
  }
Beispiel #3
0
  // 修改:属性值,文本
  public static void main(String[] args) throws Exception {
    Document doc = new SAXReader().read(new File("C:/Users/Administrator/Desktop/contact.xml"));

    // 方案一: 修改属性值   1.得到标签对象 2.得到属性对象 3.修改属性值
    // 1.1  得到标签对象
    Element contactElem = doc.getRootElement().element("contact");
    // 1.2 得到属性对象
    Attribute idAttr = contactElem.attribute("id");
    // 1.3 修改属性值
    idAttr.setValue("003");

    // 方案二: 修改属性值
    // 1.1  得到标签对象
    Element contactElem1 = doc.getRootElement().element("contact");
    // 1.2 通过增加同名属性的方法,修改属性值
    contactElem.addAttribute("id", "004");

    // 修改文本 1.得到标签对象 2.修改文本
    Element nameElem = doc.getRootElement().element("contact").element("name");
    nameElem.setText("demo7");

    FileOutputStream out = new FileOutputStream("C:/Users/Administrator/Desktop/test/contact.xml");
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("utf-8");
    XMLWriter writer = new XMLWriter(out, format);
    writer.write(doc);
    writer.close();
  }
  public static void main(String[] args) throws DocumentException {
    Document doc = DocumentHelper.createDocument();
    Element ebank = doc.addElement("ebank");
    Element gDecl = ebank.addElement("gDecl");
    gDecl.setText("");
    Element data = ebank.addElement("gTxData");
    Element cHostCod = data.addElement("cHostCod");
    cHostCod.setText("820001");
    Element cRspCod = data.addElement("cRspCod");
    cRspCod.setText("SC0000");
    Element rescode = data.addElement("rescode");
    rescode.setText("ISS0000");
    Element resmsg = data.addElement("resmsg");
    resmsg.setText("成功");

    try {
      OutputFormat format = OutputFormat.createPrettyPrint();
      format.setEncoding("GB2312");
      XMLWriter writer = new XMLWriter(new FileOutputStream("src/output.xml"), format);
      writer.write(doc);
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

    System.out.println("已成功创建XML文件...");
  }
  private void ajaxResponse(String htmlSource) {

    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("text/html;charset=utf-8");
    response.setHeader("Cache-control", "no-cache");
    response.setHeader("pragma", "no-cache");
    // 拿到一个输出的对象
    PrintWriter out = null;
    try {
      out = response.getWriter();
      // 格式化输出
      OutputFormat oFormat = new OutputFormat();
      oFormat.setEncoding("utf-8");
      XMLWriter xmlWriter = new XMLWriter(out);
      xmlWriter.write(htmlSource);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

    } finally {
      out.flush();
      out.close();
    }
  }
Beispiel #6
0
 /**
  * 将document写入xml文件中
  *
  * @param document
  * @param xmlFile
  * @return
  */
 public boolean docToXmlFile(Document document, String xmlFile) {
   // 删除生成文件名中的中文字符
   xmlFile = xmlFile.replaceAll("([\u4E00-\u9FA5]+)|([\u4E00-\u9FA5]+)", "");
   try {
     // 排版缩进的格式
     OutputFormat format = OutputFormat.createPrettyPrint();
     // 设置编码,可按需设置
     format.setEncoding("gb2312");
     // 创建XMLWriter对象,指定了写出文件及编码格式
     XMLWriter writer =
         new XMLWriter(
             new OutputStreamWriter(new FileOutputStream(new File(xmlFile)), "gb2312"), format);
     // 写入
     writer.write(document);
     // 立即写入
     writer.flush();
     // 关闭操作
     writer.close();
     System.out.println("输出xml文件到:" + xmlFile);
     return true;
   } catch (IOException e) {
     e.printStackTrace();
     return false;
   }
 }
 private void addXmlAnnotations(ModelAndView mav, String style) {
   List<ConceptAnnotation> annotations =
       (List<ConceptAnnotation>) mav.getModel().get("annotations");
   mav.addObject("mimetype", "text/xml");
   if (annotations != null) {
     Document doc = DocumentFactory.getInstance().createDocument();
     Element mappings = doc.addElement("mappings");
     for (ConceptAnnotation annotation : annotations) {
       Element mapping = mappings.addElement("mapping");
       mapping.addAttribute("id", String.valueOf(annotation.getOid()));
       mapping.addAttribute("start", String.valueOf(annotation.getBegin()));
       mapping.addAttribute("end", String.valueOf(annotation.getEnd()));
       mapping.addAttribute("pname", annotation.getPname());
       mapping.addAttribute("group", annotation.getStygroup());
       mapping.addAttribute("codes", StringUtils.replace(annotation.getStycodes(), "\"", ""));
       mapping.setText(annotation.getCoveredText());
     }
     OutputFormat outputFormat =
         "compact".equals(style)
             ? OutputFormat.createCompactFormat()
             : OutputFormat.createPrettyPrint();
     StringWriter swriter = new StringWriter();
     XMLWriter writer = new XMLWriter(swriter, outputFormat);
     try {
       writer.write(doc);
       writer.flush();
       mav.addObject("stringAnnotations", swriter.toString());
     } catch (IOException e) {
       logger.warn("IOException writing XML to buffer", e);
     }
   }
 }
Beispiel #8
0
 /**
  * 保存文档
  *
  * @param doc
  * @param xmlPath
  * @param encoding
  * @throws Exception
  */
 public static void save(Document doc, String xmlPath, String encoding) throws Exception {
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setEncoding(encoding);
   XMLWriter writer =
       new XMLWriter(new OutputStreamWriter(new FileOutputStream(xmlPath), encoding), format);
   writer.write(doc);
   writer.flush();
   writer.close();
 }
Beispiel #9
0
 /**
  * 写dom文档
  *
  * @throws IOException
  */
 public static void saveDocument(Document doc, FileWriter writer) throws IOException {
   //  输出全部原始数据,在编译器中显示
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setIndent("    ");
   format.setEncoding("UTF-8"); // 根据需要设置编码
   XMLWriter xmlWriter = new XMLWriter(writer, format);
   xmlWriter.write(doc);
   xmlWriter.close();
 }
  public void getXMLWrite(Document document, String filePath) throws Exception {

    OutputFormat of = new OutputFormat(" ", true);
    of.setEncoding("UTF-8");
    XMLWriter xw = new XMLWriter(new FileWriter(filePath), of);
    xw.setEscapeText(false);
    xw.write(document);
    xw.close();
    System.out.println(document.asXML());
  }
Beispiel #11
0
  public static void write2Xml(Document document) throws IOException {

    // 漂亮的格式输出器,设置格式输出为UTF-8
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");

    XMLWriter writer = new XMLWriter(new FileOutputStream(filepath), format);
    writer.write(document);
    writer.close();
  }
 /**
  * 将document 对象写入指定的文件
  *
  * @param xml
  * @param fileName
  */
 public static void dumpToFile(Node xml, String fileName) {
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setEncoding("GBK");
   try {
     XMLWriter writer = new XMLWriter(new FileWriter(fileName), format);
     writer.write(xml);
     writer.close();
   } catch (IOException e) {
     log.error("将document 对象写入指定的文件时出现IO错误 !", e);
   }
 }
Beispiel #13
0
  /**
   * xml转换为字符串
   *
   * @param doc
   * @param encoding
   * @return
   * @throws Exception
   */
  public static String toString(Document doc, String encoding) throws Exception {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(encoding);
    ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
    XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteOS, encoding), format);
    writer.write(doc);
    writer.flush();
    writer.close();
    writer = null;

    return byteOS.toString(encoding);
  }
Beispiel #14
0
 /**
  * @param config The configuration to write as XML
  * @param out The stream to write the configuration to
  * @throws java.io.IOException If an error occurs writing the XML document
  */
 public static void writeAsXml(MutableConfig config, java.io.OutputStream out)
     throws java.io.IOException {
   org.dom4j.DocumentFactory df = org.dom4j.DocumentFactory.getInstance();
   Element root = config.toXML(df);
   org.dom4j.Document doc = df.createDocument(root);
   org.dom4j.io.OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
   format.setIndent("\t");
   org.dom4j.io.XMLWriter writer;
   writer = new org.dom4j.io.XMLWriter(out, format);
   writer.write(doc);
   writer.flush();
 }
Beispiel #15
0
 public void stringXMLToFile(String filePath, String content) {
   try {
     OutputFormat format = OutputFormat.createPrettyPrint();
     format.setEncoding("UTF-8");
     XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(filePath), format);
     Document doc = DocumentHelper.parseText(content);
     xmlWriter.write(doc);
     xmlWriter.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 /**
  * 将xml元素输出到控制台
  *
  * @param xml
  */
 public static void dump(Node xml) {
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setEncoding("GBK");
   XMLWriter writer;
   try {
     writer = new XMLWriter(System.out, format);
     writer.write(xml);
     writer.flush();
     // do not call writer.close(); !
   } catch (Throwable t) {
     // otherwise, just dump it
     System.out.println(xml.asXML());
   }
 }
Beispiel #17
0
  // Logs a new entry in the library RSS file
  public static synchronized void addRSSEntry(
      String title, String link, String description, File rssFile) {
    // File rssFile=new File("nofile.xml");

    try {
      System.out.println("Looking for RSS file: " + rssFile.getCanonicalPath());
      if (rssFile.exists()) {

        SAXReader reader = new SAXReader();
        Document document = reader.read(rssFile);
        Element root = document.getRootElement();
        Element channel = root.element("channel");
        List items = channel.elements("item");
        int numItems = items.size();
        items = null;
        if (numItems > 9) {
          Element removeThisItem = channel.element("item");
          channel.remove(removeThisItem);
        }

        Element newItem = channel.addElement("item");
        Element newTitle = newItem.addElement("title");
        Element newLink = newItem.addElement("link");
        Element newDescription = newItem.addElement("description");
        newTitle.setText(title);
        newDescription.setText(description);
        newLink.setText(link);

        Element pubDate = channel.element("pubDate");
        pubDate.setText((new java.util.Date()).toString());

        // now save changes
        FileWriter mywriter = new FileWriter(rssFile);
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));
        XMLWriter writer = new XMLWriter(mywriter, format);
        writer.write(document);
        writer.close();
      }
    } catch (IOException ioe) {
      System.out.println("ERROR: Could not find the RSS file.");
      ioe.printStackTrace();
    } catch (DocumentException de) {
      System.out.println("ERROR: Could not read the RSS file.");
      de.printStackTrace();
    } catch (Exception e) {
      System.out.println("Unknown exception trying to add an entry to the RSS file.");
      e.printStackTrace();
    }
  }
 /**
  * 保存xml文件;
  *
  * @param document xml文件流;
  * @param filePath 文件存储的全路径(包括文件名)
  * @code 储存的编码;
  */
 public void saveXmlFile(Document document, String filePath, String code) {
   if (document == null) {
     return;
   }
   XMLWriter output;
   try {
     OutputFormat format = new OutputFormat();
     format.setEncoding(code);
     output = new XMLWriter(new FileWriter(new File(filePath)), format);
     output.write(document);
     output.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Beispiel #19
0
  /**
   * Write the report XML document out to file
   *
   * @param reportDir Directory to hold report file.
   */
  public void save(File reportDir) throws BuildException {
    try {
      // Open the file matching the parameter suite
      final File file = new File(reportDir, FILENAME_PREFIX + suite + FILENAME_EXTENSION);

      // Retrieve the root element and adjust the failures and test attributes
      Element root = document.getRootElement();
      root.addAttribute(FAILURE_ATTRIBUTE_LABEL, String.valueOf(suite.getFailures()));
      root.addAttribute(ERROR_ATTRIBUTE_LABEL, String.valueOf(suite.getErrors()));
      root.addAttribute(TESTS_ATTRIBUTE_LABEL, String.valueOf(suite.getTests()));
      root.addAttribute(IGNORE_ATTRIBUTE_LABEL, String.valueOf(suite.getSkips()));
      root.addAttribute(TIME_ATTRIBUTE_LABEL, String.valueOf(formatTime(suite.getTime())));
      root.addAttribute(HOSTNAME_ATTRIBUTE_LABEL, getHostname());

      final String timestamp = DateUtils.format(new Date(), DateUtils.ISO8601_DATETIME_PATTERN);
      root.addAttribute(TIMESTAMP_ATTRIBUTE_LABEL, timestamp);

      // Write the updated suite
      final OutputFormat format = OutputFormat.createPrettyPrint();
      final XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
      writer.write(document);
      writer.close();
    } catch (Exception e) {
      throw new BuildException(ERROR_SAVING_REPORT, e);
    }
  }
  /** Saves the configuration on local drive. Usually you needn't to call this on your own. */
  public void save() {
    Document xmlDocument = DocumentHelper.createDocument();
    Element root = xmlDocument.addElement("config");

    for (String id : config.keySet()) {
      Element tool = root.addElement("key");
      tool.addAttribute("id", id);
      tool.addAttribute("value", config.get(id));
    }

    try {
      OutputFormat format = OutputFormat.createPrettyPrint();

      if (!Key.KEY_CONFIG_FILE.exists()) {
        Key.KEY_CONFIG_FILE.getParentFile().mkdirs();
        Key.KEY_CONFIG_FILE.createNewFile();
      }

      XMLWriter writer = new XMLWriter(new FileWriter(Key.KEY_CONFIG_FILE), format);

      writer.write(xmlDocument);
      writer.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ChessXMLService service = new ChessXMLServiceImpl();
    String from = (String) request.getParameter("from");
    String to = (String) request.getParameter("to");

    ChessPlay play = new ChessPlay();
    play.setColumnFrom(getColumnFrom(from));
    play.setColumnTo(getColumnFrom(to));
    play.setRowFrom(new Integer(getRowFrom(from)));
    play.setRowTo(new Integer(getRowFrom(to)));

    response.setContentType("text/xml");

    Document doc = service.playWhite(play);
    Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(out, format);

    try {
      writer.write(doc);
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      writer.close();
    }
  }
Beispiel #22
0
 {
   try {
     writer = new XMLWriter(OutputFormat.createPrettyPrint());
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
 }
  public static void setupLocalSolver(String codeBase, String host, int port) {
    if (sInstance == null || sLocalSolverInitialized) return;
    synchronized (sInstance) {
      try {
        File webInfDir = new File(ApplicationProperties.getBasePath());
        File timetablingDir = webInfDir.getParentFile();
        File solverDir = new File(timetablingDir, "solver");
        File solverJnlp = new File(solverDir, "solver.jnlp");

        Document document = (new SAXReader()).read(solverJnlp);
        Element root = document.getRootElement();
        root.attribute("codebase")
            .setValue(codeBase + (codeBase.endsWith("/") ? "" : "/") + "solver");

        boolean hostSet = false, portSet = false;
        Element resources = root.element("resources");
        for (Iterator i = resources.elementIterator("property"); i.hasNext(); ) {
          Element property = (Element) i.next();
          if ("tmtbl.solver.register.host".equals(property.attributeValue("name"))) {
            property.attribute("value").setValue(host);
            hostSet = true;
          }
          if ("tmtbl.solver.register.port".equals(property.attributeValue("name"))) {
            property.attribute("value").setValue(String.valueOf(port));
            portSet = true;
          }
        }

        if (!hostSet) {
          resources
              .addElement("property")
              .addAttribute("name", "tmtbl.solver.register.host")
              .addAttribute("value", host);
        }
        if (!portSet) {
          resources
              .addElement("property")
              .addAttribute("name", "tmtbl.solver.register.port")
              .addAttribute("value", String.valueOf(port));
        }

        FileOutputStream fos = null;
        try {
          fos = new FileOutputStream(solverJnlp);
          (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
          fos.flush();
          fos.close();
          fos = null;
        } finally {
          try {
            if (fos != null) fos.close();
          } catch (IOException e) {
          }
        }
      } catch (Exception e) {
        sLog.debug("Unable to alter solver.jnlp, reason: " + e.getMessage(), e);
      }
      sLocalSolverInitialized = true;
    }
  }
  /** 生成xml文件; */
  public void createXMLFile() throws IOException {
    // 使用 DocumentHelper 类创建一个文档实例。 DocumentHelper 是生成 XML 文档节点的 dom4j API
    // 工厂类。
    Document document = DocumentHelper.createDocument();

    // 使用 addElement() 方法创建根元素 catalog 。addElement() 用于向 XML 文档中增加元素。
    Element catalogElement = document.addElement("catalog");
    // 在 catalog 元素中使用 addComment() 方法添加注释“An XML catalog”。
    catalogElement.addComment("An XML Catalog");
    // 在 catalog 元素中使用 addProcessingInstruction() 方法增加一个处理指令。
    catalogElement.addProcessingInstruction("target", "text");

    // 在 catalog 元素中使用 addElement() 方法增加 journal 元素。
    Element journal = catalogElement.addElement("journal");
    // 使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 属性。
    journal.addAttribute("title", "XML Zone");
    journal.addAttribute("publisher", "IBM Devoloperment");

    // 添加节点journal的子节点article,并设置其属性;
    Element articleElement = journal.addElement("article");
    articleElement.addAttribute("level", "Intermediate");
    articleElement.addAttribute("date", "December-2008");

    // 添加节点articleElement的子结点title,并使用 setText() 方法设置其元素的文本。
    Element titleElement = articleElement.addElement("title");
    titleElement.setText("又是下雨天");

    // 添加节点articleElement的子结点author.添加子结点的子结点firstname、lastname,并设置其文件;
    Element authorElement = articleElement.addElement("author");
    Element firstNameElement = authorElement.addElement("firstname");
    firstNameElement.setText("Marcello");
    Element lastNameElement = authorElement.addElement("lastname");
    lastNameElement.setText("Vitaletti");

    // 可以使用 addDocType() 方法添加文档类型说明。

    OutputFormat format = new OutputFormat();
    format.setEncoding("gb2312");
    /**
     * write into a file XMLWriter output = new XMLWriter( new FileWriter(new File("catalog.xml")),
     * format);
     */
    XMLWriter output = new XMLWriter(System.out, format);
    output.write(document);
    output.close();
  }
Beispiel #25
0
 /** 将doc的内容写入到qbPath里 */
 public static void writeXml(Document doc, String qbPath) {
   FileOutputStream fileOut = null;
   try {
     fileOut = new FileOutputStream(qbPath);
     OutputFormat format = OutputFormat.createPrettyPrint();
     format.setEncoding("GB2312");
     format.setIndent(true);
     format.setIndent(" ");
     XMLWriter writer = new XMLWriter(fileOut, format);
     writer.write(doc);
     writer.flush();
     writer.close();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  /**
   * 通过XSD(XML Schema)校验XML
   *
   * @throws FileNotFoundException
   */
  public boolean validateXMLByXSD(String testXSD, String xmlFileName) throws FileNotFoundException {
    //        String xmlFileName = "Q:\\_dev_stu\\xsdtest\\src\\note.xml";
    String xsdFileName = "E:/datashare/" + testXSD;
    FileInputStream fls = new FileInputStream(new File(xmlFileName));
    try {

      // 创建默认的XML错误处理器
      XMLErrorHandler errorHandler = new XMLErrorHandler();
      // 获取基于 SAX 的解析器的实例
      SAXParserFactory factory = SAXParserFactory.newInstance();
      // 解析器在解析时验证 XML 内容。
      factory.setValidating(true);
      // 指定由此代码生成的解析器将提供对 XML 名称空间的支持。
      factory.setNamespaceAware(true);
      // 使用当前配置的工厂参数创建 SAXParser 的一个新实例。
      SAXParser parser = factory.newSAXParser();
      // 创建一个读取工具
      SAXReader xmlReader = new SAXReader();
      // 获取要校验xml文档实例
      Document xmlDocument = (Document) xmlReader.read(fls);
      // 设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在
      // [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。
      parser.setProperty(
          "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
          "http://www.w3.org/2001/XMLSchema");
      parser.setProperty(
          "http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdFileName);
      // 创建一个SAXValidator校验工具,并设置校验工具的属性
      SAXValidator validator = new SAXValidator(parser.getXMLReader());
      // 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。
      validator.setErrorHandler(errorHandler);
      // 校验
      validator.validate(xmlDocument);

      XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
      // 如果错误信息不为空,说明校验失败,打印错误信息
      if (errorHandler.getErrors().hasContent()) {
        System.out.println("XML文件校验失败!");
        writer.write(errorHandler.getErrors());
        return false;
      } else {
        System.out.println("XML文件校验成功!");
        return true;
      }
    } catch (Exception ex) {
      System.out.println(
          "XML文件: " + xmlFileName + " 通过XSD文件:" + xsdFileName + "检验失败。\n原因: " + ex.getMessage());
      // ex.printStackTrace();
      return false;
    } finally {
      try {
        fls.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
 /**
  * Utility to serialize Document as a String for debugging
  *
  * @param document document
  * @return xml string
  * @throws IOException if error occurs
  */
 private static String serialize(final Document document) throws IOException {
   final OutputFormat format = OutputFormat.createPrettyPrint();
   final StringWriter sw = new StringWriter();
   final XMLWriter writer = new XMLWriter(sw, format);
   writer.write(document);
   writer.flush();
   sw.flush();
   return sw.toString();
 }
Beispiel #28
0
 public String toString() {
   StringWriter out = new StringWriter();
   XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
   try {
     writer.write(element);
   } catch (Exception e) {
     // Ignore.
   }
   return out.toString();
 }
 private void prettyPrint(Element element) {
   // System.out.println( element.asXML() );
   try {
     OutputFormat format = OutputFormat.createPrettyPrint();
     new XMLWriter(System.out, format).write(element);
     System.out.println();
   } catch (Throwable t) {
     System.err.println("Unable to pretty print element : " + t);
   }
 }
Beispiel #30
0
  /** @param args */
  public static void main(String[] args) throws Exception {
    SAXReader reader = new SAXReader();
    Document doc = reader.read("tds.xml");

    StringWriter sw = new StringWriter();

    XMLWriter writer = new XMLWriter(sw, OutputFormat.createPrettyPrint());
    writer.write(doc);
    System.out.println(sw.toString());
  }