/** 保存文件 */
 public int writeModelXml(Hashtable has, Hashtable hat) {
   int done = 1;
   try {
     for (int i = 0; i < has.size(); i++) {
       String[] str1 = ((String) has.get(i)).split(",");
       System.out.println(str1.length);
       // 创建节点 node;
       String index = str1[2];
       String direction = (String) hat.get(i);
       index = index.replaceAll("index", "");
       addNodes(index, "image/up_green.gif", str1[0], str1[1], direction);
     }
     Format format = Format.getCompactFormat();
     format.setEncoding("GB2312");
     format.setIndent("	");
     serializer = new XMLOutputter(format);
     fos = new FileOutputStream(fullPath);
     fos.write(headBytes.getBytes());
     serializer.output(doc, fos);
     fos.close();
   } catch (Exception e) {
     done = 0;
     e.printStackTrace();
     SysLogger.error("Error in XmlOperator.close()", e);
   }
   return done;
 }
 public String createTable() {
   Element root = new Element("table");
   root.setAttribute("border", "0");
   Document doc = new Document(root);
   Element thead = new Element("thead");
   Element th = new Element("th");
   th.addContent("A header");
   th.setAttribute("class", "aka_header_border");
   thead.addContent(th);
   Element th2 = new Element("th");
   th2.addContent("Another header");
   th2.setAttribute("class", "aka_header_border");
   thead.addContent(th2);
   root.addContent(thead);
   Element tr1 = new Element("tr");
   Element td1 = new Element("td");
   td1.setAttribute("valign", "top");
   td1.setAttribute("class", "cellBorders");
   td1.setText("cell contents");
   tr1.addContent(td1);
   root.addContent(tr1);
   XMLOutputter outp = new XMLOutputter();
   Format format = Format.getPrettyFormat();
   format.setOmitDeclaration(true);
   outp.setFormat(format);
   Writer writer = new StringWriter();
   try {
     outp.output(doc, writer);
   } catch (IOException e) {
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   }
   return writer.toString();
 }
Example #3
0
  public void convertPageToXML(Page page) {
    try {
      for (Question ques : page.items) {
        Element newQues = new Element("DOC");
        Element docNo = new Element("DOCNO");
        Element docUrl = new Element("DOCURL");

        String link = ques.link;
        String quesitonID = link.split("/")[4];
        docNo.setText(quesitonID);
        docUrl.setText(link);
        newQues.addContent(docNo);
        newQues.addContent(docUrl);

        MyParser myParser = new MyParser();
        MyQuestion myQues = myParser.parseStacakOverFlowUrl(link);

        Element title = new Element("title");
        title.setText(myQues.title);
        newQues.addContent(title);

        Element content = new Element("p");
        content.setText(myQues.content);
        newQues.addContent(content);

        Element answers = new Element("answers");
        for (MyAnswer ans : myQues.answers) {
          Element answer = new Element("answer");

          Element votes = new Element("votes");
          votes.setText(ans.votes);
          answer.addContent(votes);

          Element text = new Element("p");
          text.setText(ans.content);
          answer.addContent(text);

          answers.addContent(answer);
        }
        newQues.addContent(answers);

        rootElement.addContent(newQues);
      }

      Document document = new Document(rootElement);
      Format format = Format.getCompactFormat();
      format.setIndent("");
      XMLOutputter xmloutputter = new XMLOutputter(format);
      OutputStream outputStream;
      outputStream = new FileOutputStream("document.xml");
      xmloutputter.output(document, outputStream);
      System.out.println("xml文档生成成功!");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #4
0
  static {
    final Format rawFormat = Format.getRawFormat();
    // JDOM has \r\n hardcoded
    rawFormat.setLineSeparator("\n");
    OUTPUTTER = new XMLOutputter(rawFormat);

    BUILDER = new SAXBuilder();
    BUILDER.setValidation(false);
  }
Example #5
0
 /*     */ private void outputDocumentToFile(Document myDocument, String path) {
   /*     */ try {
     /* 242 */ Format format = Format.getCompactFormat();
     /* 243 */ format.setEncoding("UTF-8");
     /* 244 */ format.setIndent("    ");
     /* 245 */ XMLOutputter outputter = new XMLOutputter(format);
     /* 246 */ outputter.output(myDocument, new FileOutputStream(path));
     /*     */ } catch (IOException e) {
     /* 248 */ e.printStackTrace();
     /*     */ }
   /*     */ }
Example #6
0
  protected final void command_set_format(Format fmt) {
    // get the current encoding
    String enc = format.getEncoding();
    // Update the format
    format = (Format) fmt.clone();
    // put the current encoding back
    format.setEncoding(enc);

    // update outputter
    xmloutputter.setFormat(format);
    System.out.printf("Format set\n");
  } // command_set_format()
Example #7
0
  protected final void command_set_indent(String indent) {
    if (indent.equals("null")) {
      format.setIndent(null);
      System.out.printf("Indentation unset", indent);
    } else {
      format.setIndent(indent);
      System.out.printf("Indentation set to \"%s\"\n", indent);
    }

    // update outputter
    xmloutputter.setFormat(format);
  } // command_set_indent()
  @Override
  public void generate(final File reportsDir, final VersionManagerSession session)
      throws VManException {
    Map<VersionlessProjectKey, Set<Plugin>> missingPlugins = session.getUnmanagedPluginRefs();
    if (missingPlugins.isEmpty()) {
      return;
    }
    Element plugins = new Element("plugins");

    for (Map.Entry<VersionlessProjectKey, Set<Plugin>> pluginsEntry : missingPlugins.entrySet()) {
      if (plugins.getContentSize() > 0) {
        plugins.addContent("\n\n");
      }

      plugins.addContent(new Comment("START: " + pluginsEntry.getKey()));

      for (Plugin dep : pluginsEntry.getValue()) {
        Element d = new Element("plugin");
        plugins.addContent(d);

        d.addContent(new Element("groupId").setText(dep.getGroupId()));
        d.addContent(new Element("artifactId").setText(dep.getArtifactId()));
        d.addContent(new Element("version").setText(dep.getVersion()));
      }

      plugins.addContent(new Comment("END: " + pluginsEntry.getKey()));
    }

    Element build = new Element("build");
    build.addContent(new Element("pluginManagement").setContent(plugins));

    Document doc = new Document(build);

    Format fmt = Format.getPrettyFormat();
    fmt.setIndent("  ");
    fmt.setTextMode(TextMode.PRESERVE);

    XMLOutputter output = new XMLOutputter(fmt);

    File report = new File(reportsDir, ID + ".xml");
    FileWriter writer = null;
    try {
      reportsDir.mkdirs();

      writer = new FileWriter(report);
      output.output(doc, writer);
    } catch (IOException e) {
      throw new VManException("Failed to generate %s report! Error: %s", e, ID, e.getMessage());
    } finally {
      closeQuietly(writer);
    }
  }
 /** 保存文件 */
 public void writeXml() {
   try {
     Format format = Format.getCompactFormat();
     format.setEncoding("GB2312");
     format.setIndent("	");
     serializer = new XMLOutputter(format);
     fos = new FileOutputStream(fullPath);
     fos.write(headBytes.getBytes());
     serializer.output(doc, fos);
     fos.close();
   } catch (Exception e) {
     e.printStackTrace();
     SysLogger.error("Error in XmlOperator.close()", e);
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see gov.nih.nci.codegen.framework.Transformer#execute(javax.jmi.reflect.RefObject,
   *      java.util.Collection)
   */
  public Collection execute(RefObject modelElement, Collection artifacts)
      throws TransformationException {
    if (modelElement == null) {
      log.error("model element is null");
      throw new TransformationException("model element is null");
    }
    if (!(modelElement instanceof Model)) {
      log.error("model element not instance of Model");
      throw new TransformationException("model element not instance of Model");
    }
    ArrayList newArtifacts = new ArrayList();
    UML13ModelElementFilter meFilt = new UML13ModelElementFilter();
    ArrayList umlExtentCol = new ArrayList();
    umlExtentCol.add(modelElement.refOutermostPackage());
    Collection classifiers = null;
    try {
      classifiers = _classifierFilt.execute(meFilt.execute(umlExtentCol));
    } catch (FilteringException ex) {
      log.error("couldn't filter model elements " + ex.getMessage());
      throw new TransformationException("couldn't filter model elements", ex);
    }
    Document doc = generateConfig(classifiers);
    XMLOutputter p = new XMLOutputter();
    p.setFormat(Format.getPrettyFormat());

    newArtifacts.add(new BaseArtifact("hibernate_config", modelElement, p.outputString(doc)));
    return newArtifacts;
  }
 /**
  * @param selected
  * @param targetFile
  * @throws IOException
  */
 private void performSave(Archetype selected, File targetFile) throws IOException {
   XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
   FileWriter writer = new FileWriter(targetFile, false);
   outputter.output(selected.getXML(), writer);
   writer.flush();
   writer.close();
 }
Example #12
0
  public static void main(String[] args) throws Exception {
    Document document = new Document();

    Element root = new Element("��ϵ���б�").setAttribute(new Attribute("��˾", "A����"));

    document.addContent(root);

    Element contactPerson = new Element("��ϵ��");

    root.addContent(contactPerson);

    contactPerson
        .addContent(new Element("����").setText("����"))
        .addContent(new Element("��˾").setText("A��˾"))
        .addContent(new Element("�绰").setText("010-55556666"))
        .addContent(
            new Element("��ַ")
                .addContent(new Element("�ֵ�").setText("5��"))
                .addContent(new Element("����").setText("�Ϻ�"))
                .addContent(new Element("ʡ��").setText("�Ϻ���")));

    XMLOutputter output =
        new XMLOutputter(Format.getPrettyFormat().setIndent("    ").setEncoding("gbk"));

    output.output(document, new FileWriter("contact.xml"));
  }
 public void unregisterExtension(String pluginName, Element extensionElement) {
   String epName = extractEPName(extensionElement);
   if (!myExtensionElement2extension.containsKey(extensionElement)) {
     XMLOutputter xmlOutputter = new XMLOutputter();
     Format format =
         Format.getCompactFormat().setIndent("  ").setTextMode(Format.TextMode.NORMALIZE);
     xmlOutputter.setFormat(format);
     StringWriter stringWriter = new StringWriter();
     try {
       xmlOutputter.output(extensionElement, stringWriter);
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
     myLogger.warn(stringWriter.toString());
     throw new IllegalArgumentException(
         "Trying to unregister extension element that was never registered");
   }
   ExtensionComponentAdapter adapter = myExtensionElement2extension.remove(extensionElement);
   if (adapter == null) return;
   if (getExtensionPoint(epName).unregisterComponentAdapter(adapter)) {
     MutablePicoContainer pluginContainer = internalGetPluginContainer();
     pluginContainer.unregisterComponent(adapter.getComponentKey());
     if (pluginContainer.getComponentAdapters().isEmpty()) {
       disposePluginContainer(pluginName);
     }
   }
 }
Example #14
0
  /**
   * @param file
   * @throws IOException
   */
  public void write(final File file) throws IOException {
    Element root = new Element("FlowDescription");
    Document flowGraph = new Document(root);

    Element units = new Element("Units");
    root.addContent(units);

    for (Node node : getUnitList()) {
      Element unitElement = new Element("Unit");
      units.addContent(unitElement);

      writeXMLNode(node, unitElement);
    } // end node

    // now for connections
    Element connectionsElement = new Element("Connections");
    root.addContent(connectionsElement);

    for (Connection connection : getConnectionList()) {
      writeXMLConnection(connectionsElement, connection);
    }

    // output
    FileOutputStream fos = new FileOutputStream(file);
    new XMLOutputter(Format.getPrettyFormat()).output(flowGraph, fos);
  }
Example #15
0
  @Override
  public void saveAllTasks(Collection<Task> tasks) {

    try {
      doc = new Document(new Element("tasks"), new DocType("tasks", "XmlDTD.dtd"));

      Iterator it = tasks.iterator();
      while (it.hasNext()) {
        Task task = (Task) it.next();
        doc.getRootElement()
            .addContent(
                new Element("task")
                    .setAttribute("id", task.getId())
                    .addContent(new Element("name").addContent(task.getName()))
                    .addContent(new Element("description").addContent(task.getDescription()))
                    .addContent(new Element("date").addContent(sdf.format(task.getDate()))));
      }

      XMLOutputter outPutter =
          new XMLOutputter(Format.getRawFormat().setIndent(" ").setLineSeparator("\n"));

      outPutter.output(doc, new FileWriter(config.getFileName()));

    } catch (IOException ex) {
      log.error(null, ex);
      throw new WritingFileException("Didn't write xml", ex.getCause());
    }
  }
  private void dumpUserConfigToFile(DefaultConfiguration fopUserConfiguration) {
    File dumpFile = new File(getFopWorkDirectory(), "generated-user-config.xml");

    if (!dumpFile.exists()) {
      try {
        //noinspection ResultOfMethodCallIgnored
        dumpFile.createNewFile();
      } catch (IOException e) {
        log.error("Unable to dump generated FOP user config", e);
      }
    }

    try {
      BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(dumpFile));

      XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat().setIndent("  "));
      outputter.output(
          new DOMBuilder().build(ConfigurationUtil.toElement(fopUserConfiguration)), outputStream);
    } catch (FileNotFoundException e) {
      // should never ever happen, see checks above..
      throw new JDocBookProcessException(
          "unable to open file for writing generated FOP user-config", e);
    } catch (IOException e) {
      log.info("Unable to write generated FOP user-config to file", e);
    }
  }
 static void writeXMLfile(String fichier) {
   try {
     XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
     sortie.output(document, new FileOutputStream(fichier));
   } catch (java.io.IOException e) {
   }
 }
Example #18
0
  public static void main(String[] args) throws IOException {
    if (args.length != 2) {
      throw new RuntimeException("Usage: FitsJarMain <fits-config-dir> <input-file>");
    }

    File file = new File(args[1]);
    String filePath = file.getAbsolutePath();
    File configDir = new File(args[0]);
    String configDirPath = configDir.getAbsolutePath();
    if (!file.exists()) {
      throw new IllegalArgumentException("Arg file !exist: " + filePath);
    }
    if (!configDir.exists()) {
      throw new IllegalArgumentException("FITS configuration !exist: " + configDirPath);
    }

    try {
      addPath(configDir.getPath() + "/xml/nlnz");
    } catch (Exception e1) {
      e1.printStackTrace();
    }

    OutputStream out = new FileOutputStream(filePath + ".xml");
    try {
      Fits fits = new Fits(configDirPath);
      FitsOutput result = fits.examine(file);
      Document doc = result.getFitsXml();
      XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
      serializer.output(doc, out);
    } catch (FitsException e) {
      e.printStackTrace();
    } finally {
      out.close();
    }
  }
Example #19
0
  /** @return */
  public String listHighestGameScores(String contentId, int count, User u) {
    u = checkUser(u);

    Element root = new Element("scores");
    root.setAttribute("content-id", contentId);

    List<ContentLog> list = contentLogDao.queryForHighest(contentId, count);
    list.addAll(contentLogDao.queryForUserLast(contentId, u.getUserId(), 1));
    int userOrder = contentLogDao.queryForOrder(list.get(list.size() - 1).getContentLogId());
    for (int i = 0; i < list.size(); i++) {
      Element e = new Element("user");
      if (i != list.size() - 1) {
        e.setAttribute("pm", String.valueOf(i + 1));
      } else {
        e.setAttribute("pm", String.valueOf(userOrder));
      }
      e.setAttribute("nc", list.get(i).getUserName());
      e.setAttribute("fs", String.valueOf(list.get(i).getScore()));
      root.addContent(e);
    }

    Document doc = new Document();
    doc.setRootElement(root);

    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());

    return outputter.outputString(doc);
  }
Example #20
0
 /** Construction is intentionally unallowed */
 public XPathDebugger() {
   // Default to pretty format
   format = Format.getPrettyFormat();
   // Create these with a guaranteed encoding
   xmloutputter = new XMLOutputter(format);
   writer = new OutputStreamWriter(System.out);
 } // ctor
  public static void main(String[] args) {
    SAXBuilder saxBuilder = new SAXBuilder();
    try {
      Document doc = saxBuilder.build(new File("domdb.xml"));

      // 首先创建好节点
      Element eltDb = new Element("db");
      Element eltDriver = new Element("driver");
      Element eltUrl = new Element("url");
      Element eltUser = new Element("user");
      Element eltPassword = new Element("password");

      // 设置节点的值
      eltDriver.setText("com.mysql.jdbc.Driver");
      eltUrl.setText("jdbc:mysql://localhost/mySql");
      eltUser.setText("root");
      eltPassword.setText("xlc");

      // 添加到根节点
      eltDb.addContent(eltDriver);
      eltDb.addContent(eltUrl);
      eltDb.addContent(eltUser);
      eltDb.addContent(eltPassword);
      // 根节点设置属性
      eltDb.setAttribute("type", "mysql");

      Element root = doc.getRootElement();
      // root.removeChild("db");//删除节点
      root.addContent(eltDb); // 增加节点

      // 修改db节点中内容
      root.getChild("db").getChild("user").setText("system");
      root.getChild("db").getChild("password").setText("manager");

      XMLOutputter xmlOut = new XMLOutputter();

      // 设置XML格式
      Format fmt = Format.getPrettyFormat();
      fmt.setIndent("    ");
      fmt.setEncoding("utf-8");

      xmlOut.setFormat(fmt);
      xmlOut.output(doc, System.out);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Creates a single String out of the Document document
   *
   * @param document
   * @param encoding The character encoding to use. If null, a standard utf-8 encoding will be used
   * @return
   */
  public static String getStringFromDocument(Document document, String encoding) {
    if (document == null) {
      logger.warn("Trying to convert null document to String. Aborting");
      return null;
    }
    if (encoding == null) encoding = CommonUtils.encoding;

    XMLOutputter outputter = new XMLOutputter();
    Format xmlFormat = outputter.getFormat();
    if (!(encoding == null) && !encoding.isEmpty()) xmlFormat.setEncoding(encoding);
    //		xmlFormat.setOmitDeclaration(true);
    xmlFormat.setExpandEmptyElements(true);
    outputter.setFormat(xmlFormat);
    String docString = outputter.outputString(document);

    return docString;
  }
Example #23
0
 void showDoc(java.io.OutputStream out) {
   XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
   try {
     fmt.output(doc, out);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 private static void updateFile(File deploymentFile, Document doc)
     throws JDOMException, IOException {
   FileOutputStream fos = new FileOutputStream(deploymentFile);
   XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat());
   outp.output(doc, fos);
   fos.flush();
   fos.close();
 }
Example #25
0
  public static void generateKanaLessonFromPlainText(String text_in, String filename_out) {
    // parse input
    ArrayList<String> als = new ArrayList<String>();
    String sep = " ";
    String2ArrayListOfString(text_in, als, sep);
    int size = als.size() / 2;

    /*// check parsing
    for(int i=0; i<als.size(); i++){
    	System.out.println(als.get(i));
    }*/

    // create document with root element
    Document doc = new Document(new Element("lesson"));

    // create an element for each char from text_in and add it to root element
    for (int i = 0; i < size; i++) {
      // maintain data
      String ch = als.get(2 * i);
      String read = als.get(2 * i + 1);

      int ch_codepoint = ch.codePointAt(0);

      // create blank elements to ease future editing
      Element chchar = new Element("char");
      Element reading = new Element("reading");
      Element translation = new Element("translation");
      Element example = new Element("example");
      example
          .addContent(new Element("text"))
          .addContent(new Element("reading"))
          .addContent(new Element("translation"));

      // fill char with content
      chchar.setAttribute("uid", "u+" + Integer.toHexString(ch_codepoint));
      chchar.setAttribute("ch", String.valueOf(ch));

      reading.setText(read);

      chchar.addContent(reading);
      chchar.addContent(translation);
      chchar.addContent(example);

      // add char to lesson
      doc.getRootElement().addContent(chchar);
    }

    // write document to file
    try {
      XMLOutputter out = new XMLOutputter();
      out.setFormat(Format.getPrettyFormat());
      out.output(doc, new FileOutputStream(filename_out));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #26
0
  /**
   * Wrap the xml with a message tag
   *
   * @throws IOException
   * @throws JDOMException
   */
  public String wrapMessage(InputStream input, String t24User, String t24Password, String branch)
      throws JDOMException, IOException {

    SAXBuilder builder = new SAXBuilder();
    try {
      Document doc = (Document) builder.build(input);
      Element rootNode = doc.getRootElement();

      // create the message element (the wrapping tag)
      Element installer =
          new Element(
              "message",
              Namespace.getNamespace("installer", "http://www.odcgroup.com/t24/installer"));
      installer.addNamespaceDeclaration(
          Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
      installer.setAttribute(new Attribute("uid", t24User));
      installer.setAttribute(new Attribute("pwd", t24Password));
      installer.setAttribute(new Attribute("branch", branch));
      installer.setAttribute(new Attribute("object", getObjectName(rootNode.getName())));

      // replace root element
      doc.setRootElement(installer);
      installer.addContent(rootNode);

      T24DeployConsole deployBuilderConsole =
          T24ServerUIExternalCore.getDefault().getDeployBuilderConsole();
      if (deployBuilderConsole.isDisplayDebug()) {
        StringWriter prettyResult = new StringWriter();
        new XMLOutputter(Format.getPrettyFormat()).output(doc, prettyResult);
        deployBuilderConsole.printDebug(
            "Credential used for the message wrapper:" + t24User + "/" + t24Password);
        deployBuilderConsole.printDebug("Message prepared for sending:");
        deployBuilderConsole.printDebug(prettyResult.toString());
      }

      // format the result
      StringWriter result = new StringWriter();
      new XMLOutputter(Format.getCompactFormat()).output(doc, result);
      return result.toString();
    } finally {
      IOUtils.closeQuietly(input);
    }
  }
  /** {@inheritDoc} */
  public String getString() throws IOException {
    Element rootElement = m_document.getRootElement();
    processChildren(rootElement);

    m_document.setContext(m_context);

    XMLOutputter output = new XMLOutputter();

    StringWriter out = new StringWriter();

    Format fmt = Format.getRawFormat();
    fmt.setExpandEmptyElements(false);
    fmt.setLineSeparator(LINEBREAK);

    output.setFormat(fmt);
    output.outputElementContent(m_document.getRootElement(), out);

    return out.toString();
  }
Example #28
0
  protected final void command_set_textmode(String rest) {
    if (rest.equals("normalize")) {
      format.setTextMode(Format.TextMode.NORMALIZE);
    } else if (rest.equals("preserve")) {
      format.setTextMode(Format.TextMode.PRESERVE);
    } else if (rest.equals("trim")) {
      format.setTextMode(Format.TextMode.TRIM);
    } else if (rest.equals("trim_full_white")) {
      format.setTextMode(Format.TextMode.TRIM_FULL_WHITE);
    } else {
      System.out.printf("Error: unknown text mode \"%s\"", rest);
      return;
    }

    // update outputter
    xmloutputter.setFormat(format);

    System.out.printf("Text mode set: %s\n", rest);
  } // command_set_textmode()
  @Test
  public void testAudioMD_noMD5() throws Exception {

    Fits fits = new Fits();

    // First generate the FITS output
    File input = new File("testfiles/test.wav");
    FitsOutput fitsOut = fits.examine(input);

    XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
    String actualXmlStr = serializer.outputString(fitsOut.getFitsXml());

    // Read in the expected XML file
    Scanner scan = new Scanner(new File("testfiles/output/FITS_test_wav_NO_MD5.xml"));
    String expectedXmlStr = scan.useDelimiter("\\Z").next();
    scan.close();

    // Set up XMLUnit
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalizeWhitespace(true);

    Diff diff = new Diff(expectedXmlStr, actualXmlStr);

    // Initialize attributes or elements to ignore for difference checking
    diff.overrideDifferenceListener(
        new IgnoreNamedElementsDifferenceListener(
            "version",
            "toolversion",
            "dateModified",
            "fslastmodified",
            "lastmodified",
            "startDate",
            "startTime",
            "timestamp",
            "fitsExecutionTime",
            "executionTime",
            "filepath",
            "location"));

    DetailedDiff detailedDiff = new DetailedDiff(diff);

    // Display any Differences
    List<Difference> diffs = detailedDiff.getAllDifferences();
    if (!diff.identical()) {
      StringBuffer differenceDescription = new StringBuffer();
      differenceDescription.append(diffs.size()).append(" differences");

      System.out.println(differenceDescription.toString());
      for (Difference difference : diffs) {
        System.out.println(difference.toString());
      }
    }

    assertTrue("Differences in XML", diff.identical());
  }
Example #30
0
 public void saveXML(String path) {
   Document doc = new Document(getXML());
   XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat());
   BufferedWriter outputStream;
   try {
     outputStream = new BufferedWriter(new FileWriter(path));
     outp.output(doc, outputStream);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }