Ejemplo n.º 1
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();
  }
Ejemplo n.º 2
0
  @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;
    }
  }
Ejemplo n.º 3
0
  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();
    }
  }
Ejemplo n.º 4
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;
   }
 }
  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文件...");
  }
Ejemplo n.º 6
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();
 }
Ejemplo n.º 7
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();
 }
  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());
  }
Ejemplo n.º 9
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);
   }
 }
Ejemplo n.º 11
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);
  }
Ejemplo n.º 12
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());
   }
 }
Ejemplo n.º 14
0
  /**
   * 设置系统设置
   *
   * @param setting 系统设置
   */
  public static void set(Setting setting) {
    try {
      File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile();
      Document document = new SAXReader().read(shopxxXmlFile);
      List<Element> elements = document.selectNodes("/shopxx/setting");
      for (Element element : elements) {
        try {
          String name = element.attributeValue("name");
          String value = beanUtils.getProperty(setting, name);
          Attribute attribute = element.attribute("value");
          attribute.setValue(value);
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        } catch (InvocationTargetException e) {
          e.printStackTrace();
        } catch (NoSuchMethodException e) {
          e.printStackTrace();
        }
      }

      FileOutputStream fileOutputStream = null;
      XMLWriter xmlWriter = null;
      try {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding("UTF-8");
        outputFormat.setIndent(true);
        outputFormat.setIndent("	");
        outputFormat.setNewlines(true);
        fileOutputStream = new FileOutputStream(shopxxXmlFile);
        xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
        xmlWriter.write(document);
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (xmlWriter != null) {
          try {
            xmlWriter.close();
          } catch (IOException e) {
          }
        }
        IOUtils.closeQuietly(fileOutputStream);
      }

      Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
      cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 15
0
 /**
  * 保存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();
   }
 }
Ejemplo n.º 16
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();
   }
 }
Ejemplo n.º 17
0
  /** 生成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();
  }
Ejemplo n.º 18
0
  public XMLNotificationWriter(
      Writer out,
      String encoding,
      String boundary,
      Thread workingThread,
      boolean compact,
      boolean supressDecl) {
    this.out = out;
    this.boundary = boundary;
    this.workingThread = workingThread;

    OutputFormat format =
        compact ? OutputFormat.createCompactFormat() : OutputFormat.createPrettyPrint();
    format.setSuppressDeclaration(supressDecl);
    format.setEncoding(encoding);
    format.setExpandEmptyElements(!compact);
    xmlWriter = new XMLWriter(out, format);
    xStream = new XStream();
  }
 /**
  * @param doc
  * @param charset
  * @return
  * @throws IOException
  */
 public static String xmltoString(Document doc, String charset) {
   if (doc == null) {
     return "";
   }
   if (charset == null) {
     return doc.asXML();
   }
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setEncoding(charset);
   StringWriter strWriter = new StringWriter();
   XMLWriter xmlWriter = new XMLWriter(strWriter, format);
   try {
     xmlWriter.write(doc);
     xmlWriter.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return strWriter.toString();
 }
Ejemplo n.º 20
0
 /**
  * 格式化XML文档,并解决中文问题
  *
  * @param filename
  * @return
  */
 public int formatXMLFile(String filename) {
   int returnValue = 0;
   try {
     SAXReader saxReader = new SAXReader();
     Document document = saxReader.read(new File(filename));
     XMLWriter writer = null;
     /** 格式化输出,类型IE浏览一样 */
     OutputFormat format = OutputFormat.createPrettyPrint();
     /** 指定XML编码 */
     format.setEncoding("GBK");
     writer = new XMLWriter(new FileWriter(new File(filename)), format);
     writer.write(document);
     writer.close();
     /** 执行成功,需返回1 */
     returnValue = 1;
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return returnValue;
 }
Ejemplo n.º 21
0
 /** 将xml文件另存为本地文件 */
 public static boolean doc2XmlFile(Document document, String filename) {
   File newFile = new File(filename);
   if (newFile.exists()) {
     System.out.println("文件已存在,另存为xml文件失败");
     return false;
   }
   boolean flag = true;
   try {
     OutputFormat format = OutputFormat.createPrettyPrint();
     format.setEncoding("GB2312");
     FileWriter fileOut = new FileWriter(new File(filename));
     XMLWriter writer = new XMLWriter(fileOut, format);
     writer.write(document);
     writer.close();
     System.out.println("成功将xml文件存储为:" + filename);
   } catch (Exception e) {
     flag = false;
     e.printStackTrace();
   }
   return flag;
 }
  /**
   * 持久化Document
   *
   * @param doc
   * @param charset
   * @return
   * @throws Exception
   * @throws IOException
   */
  public static void xmltoFile(Document doc, File file, String charset) throws Exception {
    if (doc == null) {
      throw new NullPointerException("doc cant not null");
    }
    if (charset == null) {
      throw new NullPointerException("charset cant not null");
    }
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(charset);
    FileOutputStream os = new FileOutputStream(file);
    OutputStreamWriter osw = new OutputStreamWriter(os, charset);
    XMLWriter xmlWriter = new XMLWriter(osw, format);
    try {
      xmlWriter.write(doc);
      xmlWriter.close();
      if (osw != null) {
        osw.close();
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 23
0
  /**
   * 把xml写入 文件
   *
   * @param filePathAndName 要写入那个文件?
   * @param document 指定的xml
   * @throws IOException
   */
  public static void xieXML(String filePathAndName, Document document) {
    OutputFormat format = new OutputFormat("   ", true);
    format.setEncoding("UTF-8");
    XMLWriter xmlWriter = null;
    try {
      xmlWriter = new XMLWriter(new FileOutputStream(filePathAndName), format);
      xmlWriter.write(document);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (xmlWriter != null) {

        try {
          xmlWriter.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 24
0
  public static String generateXML(WTPart part, String directory)
      throws WTException, PropertyVetoException, IOException {
    File file = new File(directory + "/");
    if (!file.exists()) file.mkdirs();

    DocumentFactory factory = DocumentFactory.getInstance();
    Document document = factory.createDocument();

    Element root = generateRoot(part.getContainerName());
    root.add(generatePart(part, directory));
    document.setRootElement(root);

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("GBK");
    XMLWriter xmlWriter =
        new XMLWriter(
            new OutputStreamWriter(
                new FileOutputStream(directory + part.getNumber() + ".xml"), "GBK"),
            format);
    xmlWriter.write(document);
    xmlWriter.close();

    return null;
  }
Ejemplo n.º 25
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static String doParameter(
      final RepositoryFile file,
      IParameterProvider parameterProvider,
      final IPentahoSession userSession)
      throws IOException {
    ActionSequenceJCRHelper helper = new ActionSequenceJCRHelper();
    final IActionSequence actionSequence =
        helper.getActionSequence(
            file.getPath(), PentahoSystem.loggingLevel, RepositoryFilePermission.READ);
    final Document document = DocumentHelper.createDocument();
    try {
      final Element parametersElement = document.addElement("parameters");

      // noinspection unchecked
      final Map<String, IActionParameter> params =
          actionSequence.getInputDefinitionsForParameterProvider(IParameterProvider.SCOPE_REQUEST);
      for (final Map.Entry<String, IActionParameter> entry : params.entrySet()) {
        final String paramName = entry.getKey();
        final IActionParameter paramDef = entry.getValue();
        final String value = paramDef.getStringValue();
        final Class type;
        // yes, the actual type-code uses equals-ignore-case and thus allows the user
        // to specify type information in a random case. sTrInG is equal to STRING is equal to the
        // value
        // defined as constant (string)
        if (IActionParameter.TYPE_LIST.equalsIgnoreCase(paramDef.getType())) {
          type = String[].class;
        } else {
          type = String.class;
        }
        final String label = paramDef.getSelectionDisplayName();

        final String[] values;
        if (StringUtils.isEmpty(value)) {
          values = new String[0];
        } else {
          values = new String[] {value};
        }

        createParameterElement(
            parametersElement, paramName, type, label, "user", "parameters", values);
      }

      createParameterElement(
          parametersElement,
          "path",
          String.class,
          null,
          "system",
          "system",
          new String[] {file.getPath()});
      createParameterElement(
          parametersElement,
          "prompt",
          String.class,
          null,
          "system",
          "system",
          new String[] {"yes", "no"});
      createParameterElement(
          parametersElement,
          "instance-id",
          String.class,
          null,
          "system",
          "system",
          new String[] {parameterProvider.getStringParameter("instance-id", null)});
      // no close, as far as I know tomcat does not like it that much ..
      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(document);
      writer.flush();
      return outputStream.toString("utf-8");
    } catch (Exception e) {
      logger.warn(Messages.getInstance().getString("HttpWebService.ERROR_0003_UNEXPECTED"), e);
      return null;
    }
  }
Ejemplo n.º 26
0
  public void save() {
    String siteID = String.valueOf(Application.getCurrentSiteID());
    SAXReader sax = new SAXReader();
    Document doc = null;
    try {
      String configXML =
          new QueryBuilder("select ConfigXML from zcsite where id = ?", siteID).executeString();
      StringReader reader = new StringReader(configXML);
      doc = sax.read(reader);
    } catch (DocumentException e1) {
      this.Response.setLogInfo(0, "保存失败");
      e1.printStackTrace();
      return;
    }
    Element root = doc.getRootElement();
    Element ImageLibConfig = root.element("ImageLibConfig");
    if (ImageLibConfig != null) {
      root.remove(ImageLibConfig);
    }
    ImageLibConfig = root.addElement("ImageLibConfig");
    ImageLibConfig.addComment("原图水印");
    Element WaterMark =
        ImageLibConfig.addElement("WaterMark")
            .addAttribute("HasWaterMark", ($V("HasWaterMark") == null) ? "0" : $V("HasWaterMark"))
            .addAttribute("WaterMarkType", $V("WaterMarkType"))
            .addAttribute("Position", $V("Position"));
    WaterMark.addElement("Image").addAttribute("src", $V("Image"));
    WaterMark.addElement("Text")
        .addAttribute("FontName", "宋体")
        .addAttribute("FontSize", $V("FontSize"))
        .addAttribute("FontColor", $V("FontColor"))
        .addText($V("Text"));

    ImageLibConfig.addComment("多缩略图");
    int count = Integer.parseInt($V("Count"));
    Element AbbrImages =
        ImageLibConfig.addElement("AbbrImages").addAttribute("Count", String.valueOf(count));
    for (int i = 1; i <= count; ++i) {
      String index = $V("AbbrImageIndex" + i);
      Element AbbrImage =
          AbbrImages.addElement("AbbrImage")
              .addAttribute("ID", String.valueOf(i))
              .addAttribute("HasAbbrImage", $V("HasAbbrImage" + index))
              .addAttribute("SizeType", $V("SizeType" + index))
              .addAttribute("Width", $V("Width" + index))
              .addAttribute("Height", $V("Height" + index));
      WaterMark =
          AbbrImage.addElement("WaterMark")
              .addAttribute(
                  "HasWaterMark",
                  ($V("HasWaterMark" + index) == null) ? "0" : $V("HasWaterMark" + index))
              .addAttribute("WaterMarkType", $V("WaterMarkType" + index))
              .addAttribute("Position", $V("Position" + index));
      WaterMark.addElement("Image").addAttribute("src", $V("Image" + index));
      WaterMark.addElement("Text")
          .addAttribute("FontName", "宋体")
          .addAttribute("FontSize", $V("FontSize" + index))
          .addAttribute("FontColor", $V("FontColor" + index))
          .addText($V("Text" + index));
    }
    try {
      OutputFormat format = OutputFormat.createPrettyPrint();
      format.setEncoding(Constant.GlobalCharset);
      StringWriter sw = new StringWriter();
      XMLWriter writer = new XMLWriter(sw, format);
      writer.write(doc);
      writer.flush();
      writer.close();
      new QueryBuilder("update zcsite set ConfigXML=? where ID = ?", sw.toString(), siteID)
          .executeNoQuery();
    } catch (IOException e) {
      this.Response.setLogInfo(0, "保存失败");
      e.printStackTrace();
      return;
    }
    imageLibConfigMap.remove(siteID);
    getImageLibConfig(siteID);
    this.Response.setLogInfo(1, "保存成功");
  }
Ejemplo n.º 27
0
 private static OutputFormat createOutputFormat(String encoding) {
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setEncoding(encoding);
   return format;
 }
Ejemplo n.º 28
0
  public void navegar() {
    try {
      File aFile = new File(NuevoProyecto.archivo);
      SAXReader xmlReader = new SAXReader();

      // xmlReader.setEncoding("UTF-8"); // ********************************************
      xmlReader.setEncoding("iso-8859-1");

      Document doc = xmlReader.read(aFile);

      Element node = (Element) doc.selectSingleNode("//vivienda");

      for (Iterator i = node.elementIterator(); i.hasNext(); ) {
        node = (Element) i.next();

        if (!node.getName().equals("email")) {

          if (node.valueOf("@alias").equals(EstanciaNueva.seleccionado)) {
            // ESTEFANÍA: Añadido para que se coja la imagen del plano desde la carpeta
            // donde está el ejecutable. Esto se hace para que no hayan rutas absolutas
            // y si se cambia la carpeta de ejecutables de directorio, siga funcionando.
            // SIEMPRE Y CUANDO, SE MANTENGA EL MISMO NOMBRE DE LA CARPETA DONDE SE SACARON
            // LAS IMÁGENES DE LOS PLANOS AL CREAR EL PROYECTO, Y EL MISMO NOMBRE DE LA
            // IMAGEN.
            File dir_iniciall = new File("./");
            String a = dir_iniciall.getAbsolutePath();
            System.out.println("raiz=" + a);
            int ind = EstanciaNueva.imagen_e.indexOf(a);
            int lon = a.length();
            String b = EstanciaNueva.imagen_e.substring(ind + lon);
            System.out.println("ruta relativa=" + b);
            System.out.println("ruta absoluta=" + EstanciaNueva.imagen_e);
            org.dom4j.Element anadir =
                node.addElement("estancia")
                    .addAttribute(
                        "nombre",
                        EstanciaNueva.nombre_e) // .addAttribute("imagen", estancia_nueva.imagen_e)
                    .addAttribute("imagen", b);
            break;
          } // end if auxi
        } // end if
      } // end for

      String auxiliar = doc.asXML();

      FileWriter archivo;
      archivo = new FileWriter(NuevoProyecto.archivo);
      OutputFormat format = OutputFormat.createPrettyPrint();

      // format.setEncoding("UTF-8");
      format.setEncoding("iso-8859-1");

      XMLWriter writer = new XMLWriter(new FileWriter(NuevoProyecto.archivo), format);
      writer.write(doc);
      writer.close();

      //			 acciones.inicializarEstancia(estancia_nueva.nombre_e );
      Acciones.inicializarEstancia(EstanciaNueva.seleccionado, EstanciaNueva.nombre_e);

    } catch (IOException e) {
      e.printStackTrace();

    } catch (DocumentException e) {
      e.printStackTrace();
    }
  } // end navegar