content: /**
   * Copyright (C) 2024 AIDC-AI
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  package com.alibaba.langengine.core.util;
  
  import org.dom4j.Document;
  import org.dom4j.DocumentException;
  import org.dom4j.io.SAXReader;
  import org.xml.sax.InputSource;
  import org.xml.sax.SAXException;
  
  import java.io.StringReader;
  import java.util.StringTokenizer;
  
  /**
   * XmlUtils
   *
   * @author xiaoxuan.lp
   */
  public class XmlUtils {
  
      public static String DDD = "http://apache.org/xml/features/disallow-doctype-decl";
  
      public static Document parseText(String text) throws DocumentException, SAXException {
          Document result = null;
  
          SAXReader reader = new SAXReader();
          reader.setFeature(DDD,true);
          String encoding = getEncoding(text);
  
          InputSource source = new InputSource(new StringReader(text));
          source.setEncoding(encoding);
  
          result = reader.read(source);
  
          // if the XML parser doesn't provide a way to retrieve the encoding,
          // specify it manually
          if (result.getXMLEncoding() == null) {
              result.setXMLEncoding(encoding);
          }
  
          return result;
      }
  
      private static String getEncoding(String text) {
          String result = null;
  
          String xml = text.trim();
  
          if (xml.startsWith("<?xml")) {
              int end = xml.indexOf("?>");
              String sub = xml.substring(0, end);
              StringTokenizer tokens = new StringTokenizer(sub, " =\"\'");
  
              while (tokens.hasMoreTokens()) {
                  String token = tokens.nextToken();
  
                  if ("encoding".equals(token)) {
                      if (tokens.hasMoreTokens()) {
                          result = tokens.nextToken();
                      }
  
                      break;
                  }
              }
          }
  
          return result;
      }
  }
  