将任意格式的 JSON 对象转换为一个 XML 字符串（不是 HTML）
12609
function jsonToXml(json, rootTag) {

	if (!typeIs(json, 'object', 'array', 'string', 'number')) unsupportedType(json);

	var root = new XmlWrapper(rootTag || 'root');
	root.setXmlType(true);
	if (typeOf(json, 'string')) {
		root.add(json);
	} else {
		for (let name in json) {
			if (hasOwnProperty(json, item)) {
				let item = json[name];
				root.add(jsonToXml(item, name));
			}
		}
	}

	return root;
}
284051
function htmlParse() {
  var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '<div></div>';
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var transData = {}; //存放转化后的数据

  var res = {}; //返回的数据

  transData = (0, _html2json.html2json)(data, 'root', options); // console.log('解析结果是', transData);

  res = transData;
  return res;
}
568258
function xml2json( xml ) {
  try {
    var obj = {};
    if ( xml.children.length > 0 ) {
      for ( var i = 0; i < xml.children.length; i++ ) {
        var item = xml.children.item( i )
        var nodeName = item.nodeName

        if ( typeof (obj[nodeName]) == "undefined" ) {
          obj[nodeName] = xml2json( item )
        } else {
          if ( typeof (obj[nodeName].push) == "undefined" ) {
            var old = obj[nodeName]

            obj[nodeName] = []
            obj[nodeName].push( old )
          }
          obj[nodeName].push( xml2json( item ) )
        }
      }
    } else {
      obj = xml.textContent
    }
    return obj
  } catch ( e ) {
    log( "PongRss", e.message )
  }
}
1247771
private byte[] filterXML(HttpServletRequest request,
                             DataResponseWrapper response)
            throws ServletException {
        byte[] data = response.getData();
        DocumentBuilder docBuilder = null;
        Document doc = null;

        try {
            synchronized(BUILDER_FACTORY){
                docBuilder =
                        BUILDER_FACTORY.newDocumentBuilder();
            }
            doc = docBuilder.parse(new ByteArrayInputStream(data));
        } catch (Exception e) {
            throw new ServletException(e);
        }

        XPath xpath;
        synchronized(XPATH_FACTORY){
            xpath = XPATH_FACTORY.newXPath();
        }
        xpath.setNamespaceContext(TYPES_NAMESPACE);
        NodeList rows = null;
        try {
            rows =
                    (NodeList) xpath
                            .evaluate("/:result/:resultList/:objectFields/:pid",
                                      doc,
                                      XPathConstants.NODESET);
        } catch (XPathExpressionException xpe) {
            throw new ServletException("Error parsing XML for search results: ",
                                       xpe);
        }

        if (rows.getLength() == 0) {
            logger.debug("No results to filter.");

            return data;
        }

        Map<String, Node> pids = new HashMap<String, Node>();
        for (int x = 0; x < rows.getLength(); x++) {
            Node pid = rows.item(x);
            pids.put(pid.getFirstChild().getNodeValue(), pid.getParentNode());
        }

        Set<Result> results = evaluatePids(pids.keySet(), request, response);

        for (Result r : results) {
            String resource = r.getResource();
            if (resource == null || resource.isEmpty()) {
                logger.warn("This resource has no resource identifier in the xacml response results!");
            } else if (logger.isDebugEnabled()) {
                logger.debug("Checking: {}", resource);
            }

            int lastSlash = resource.lastIndexOf('/');
            String rid = resource.substring(lastSlash+1);

            if (r.getStatus().getCode().contains(Status.STATUS_OK)
                    && r.getDecision() != Result.DECISION_PERMIT) {
                Node node = pids.get(rid);
                node.getParentNode().removeChild(node);
                logger.debug("Removing: {} [{}]", resource, rid);
            }
        }
        // since namespaces are disabled, set the attribute explicitly
        doc.getDocumentElement().setAttribute("xmlns", "http://www.fedora.info/definitions/1/0/types/");
        Source src = new DOMSource(doc);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        javax.xml.transform.Result dst = new StreamResult(os);
        try {
            xFormer.transform(src, dst);
        } catch (TransformerException te) {
            throw new ServletException("error generating output", te);
        }

        return os.toByteArray();
    }
136592
function xmlValue(node) {
  if (!node) {
    return '';
  }

  var ret = '';
  if (node.nodeType == DOM_TEXT_NODE ||
      node.nodeType == DOM_CDATA_SECTION_NODE) {
    ret += node.nodeValue;

  } else if (node.nodeType == DOM_ATTRIBUTE_NODE) {
    if (ajaxsltIsIE6) {
      ret += xmlValueIE6Hack(node);
    } else {
      ret += node.nodeValue;
    }
  } else if (node.nodeType == DOM_ELEMENT_NODE ||
             node.nodeType == DOM_DOCUMENT_NODE ||
             node.nodeType == DOM_DOCUMENT_FRAGMENT_NODE) {
    for (var i = 0; i < node.childNodes.length; ++i) {
      ret += arguments.callee(node.childNodes[i]);
    }
  }
  return ret;
}
893035
public JSON read( String xml ) {
      JSON json = null;
      try{
         Document doc = new Builder().build( new StringReader( xml ) );
         Element root = doc.getRootElement();
         if( isNullObject( root ) ){
            return JSONNull.getInstance();
         }
         String defaultType = getType( root, JSONTypes.STRING );
         if( isArray( root, true ) ){
            json = processArrayElement( root, defaultType );
            if( forceTopLevelObject ){
               String key = removeNamespacePrefix( root.getQualifiedName() );
               json = new JSONObject().element( key, json );
            }
         }else{
            json = processObjectElement( root, defaultType );
            if( forceTopLevelObject ){
               String key = removeNamespacePrefix( root.getQualifiedName() );
               json = new JSONObject().element( key, json );
            }
         }
      }catch( JSONException jsone ){
         throw jsone;
      }catch( Exception e ){
         throw new JSONException( e );
      }
      return json;
   }
165353
function xml2jsonRecurse(xmlStr) {
    var obj = {},
        tagName, indexClosingTag, inner_substring, tempVal, openingTag;

    while (xmlStr.match(/<[^\/][^>]*>/)) {
        openingTag = xmlStr.match(/<[^\/][^>]*>/)[0];
        tagName = openingTag.substring(1, openingTag.length - 1);
        indexClosingTag = xmlStr.indexOf(openingTag.replace('<', '</'));

        // account for case where additional information in the openning tag
        if (indexClosingTag == -1) {

            tagName = openingTag.match(/[^<][\w+$]*/)[0];
            indexClosingTag = xmlStr.indexOf('</' + tagName);
            if (indexClosingTag == -1) {
                indexClosingTag = xmlStr.indexOf('<\\/' + tagName);
            }
        }
        inner_substring = xmlStr.substring(openingTag.length, indexClosingTag);
        if (inner_substring.match(/<[^\/][^>]*>/)) {
            tempVal = xml2json(inner_substring);
        }
        else {
            tempVal = inner_substring;
        }
        // account for array or obj //
        if (obj[tagName] === undefined) {
            obj[tagName] = tempVal;
        }
        else if (Array.isArray(obj[tagName])) {
            obj[tagName].push(tempVal);
        }
        else {
            obj[tagName] = [obj[tagName], tempVal];
        }

        xmlStr = xmlStr.substring(openingTag.length * 2 + 1 + inner_substring.length);
    }

    return obj;
}
346081
def xml_to_html(html_flag, xml_string, base_url=None):
    ""
    if not xml_string or not html_flag is True:
        return xml_string
    html_string = xml_string
    html_string = remove_comment_tags(html_string)
    #  Escape unmatched angle brackets
    if '<' in html_string or '>' in html_string:
        html_string = escape_html(html_string)
    # Replace more tags
    html_string = replace_xref_tags(html_string)
    html_string = replace_ext_link_tags(html_string)
    html_string = replace_email_tags(html_string)
    html_string = replace_inline_graphic_tags(html_string, base_url)
    html_string = replace_named_content_tags(html_string)
    html_string = replace_mathml_tags(html_string)
    html_string = replace_table_style_author_callout(html_string)
    html_string = replace_simple_tags(html_string, 'italic', 'i')
    html_string = replace_simple_tags(html_string, 'bold', 'b')
    html_string = replace_simple_tags(html_string, 'underline', 'span', '<span class="underline">')
    html_string = replace_simple_tags(html_string, 'sc', 'span', '<span class="small-caps">')
    html_string = replace_simple_tags(html_string, 'monospace', 'span', '<span class="monospace">')
    html_string = replace_simple_tags(html_string, 'inline-formula', None)
    html_string = replace_simple_tags(html_string, 'break', 'br')
    return html_string
1096727
public static void normalXmlParse(){
        String json = CrawlerPack.getFromRemote(url);
        String xml = CrawlerPack.jsonToXml(json);

        // 原始 json 轉為 xml 的結果
        System.out.println( "原始XML" ) ;
        System.out.println( xml );

        Document jsoupDoc = Jsoup.parse(xml, "", Parser.xmlParser());
        jsoupDoc.charset(StandardCharsets.UTF_8);

        // 發生了什麼事？
        System.out.println( "轉換後XML" ) ;
        System.out.println(jsoupDoc.toString());


    }
1072741
function(json, next) {
                fs.writeFile(out + "/" + path.basename(url).replace('.xml', '.json'), JSON.stringify(json), function (err) {
                    if (err) {
                        return next(err);
                    }
                    next(null, json);
                });
            }
249686
function html2json(html) {
  var bindName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'root';
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  //处理字符串
  html = (0, _index.removeDOCTYPE)(html);
  html = (0, _index.trimHtml)(html);
  html = (0, _decode["default"])(html); //生成node节点

  var bufArray = [];
  var results = {
    node: bindName,
    nodes: [],
    images: [],
    imageUrls: []
  };
  var index = 0;
  (0, _htmlparser.HTMLParser)(html, {
    start: function start(tag, attrs, unary) {
      var node = {
        node: 'element',
        tag: tag
      };

      if (bufArray.length === 0) {
        node.index = index.toString();
        index += 1;
      } else {
        var parent = bufArray[0];

        if (parent.nodes === undefined) {
          parent.nodes = [];
        }

        node.index = parent.index + '.' + parent.nodes.length;
      }

      if (_index2.block[tag]) {
        node.tagType = "block";
      } else if (_index2.inline[tag]) {
        node.tagType = "inline";
      } else if (_index2.closeSelf[tag]) {
        node.tagType = "closeSelf";
      }

      if (attrs.length !== 0) {
        node.attr = attrs.reduce(function (pre, attr) {
          var name = attr.name;
          var value = attr.value;

          if (name == 'class') {
            // console.dir(value);
            //  value = value.join("")
            node.classStr = value;
          } // has multi attibutes
          // make it array of attribute


          if (name == 'style') {
            node.styleStr = value;
          }

          if (value.match(/ /) && name !== 'style') {
            value = value.split(' ');
          } else if (value.match(/;/) && name === 'style') {
            value = value.split(';');
          } // if attr already exists
          // merge it


          if (pre[name]) {
            if (Array.isArray(pre[name])) {
              // already array, push to last
              pre[name].push(value);
            } else {
              // single value, make it array
              pre[name] = [pre[name], value];
            }
          } else {
            // not exist, put it
            pre[name] = value;
          }

          return pre;
        }, {});
      } //对img添加额外数据


      if (node.tag === 'img') {
        node.imgIndex = results.images.length;
        var imgUrl = node.attr.src;

        if (imgUrl[0] == '') {
          imgUrl.splice(0, 1);
        }

        imgUrl = (0, _index.urlToHttpUrl)(imgUrl, _index2.__placeImgeUrlHttps);
        node.attr.src = imgUrl;
        node.from = bindName; // node.bindtap = test;

        results.images.push(node);
        results.imageUrls.push(imgUrl);
      } // 处理font标签样式属性


      if (node.tag === 'font') {
        var fontSize = ['x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '-webkit-xxx-large'];
        var styleAttrs = {
          'color': 'color',
          'face': 'font-family',
          'size': 'font-size'
        };
        if (!node.attr.style) node.attr.style = [];
        if (!node.styleStr) node.styleStr = '';

        for (var key in styleAttrs) {
          if (node.attr[key]) {
            var value = key === 'size' ? fontSize[node.attr[key] - 1] : node.attr[key];
            node.attr.style.push(styleAttrs[key]);
            node.attr.style.push(value);
            node.styleStr += styleAttrs[key] + ': ' + value + ';';
          }
        }
      } //临时记录source资源


      if (node.tag === 'source') {
        results.source = node.attr.src;
      }

      if (unary) {
        // if this tag doesn't have end tag
        // like <img src="hoge.png"/>
        // add to parents
        var parent = bufArray[0] || results;

        if (parent.nodes === undefined) {
          parent.nodes = [];
        }

        parent.nodes.push(node);
      } else {
        bufArray.unshift(node);
      }

      if (!node.styleStr) {
        node.styleStr = '';
      }

      if (!node.classStr) {
        node.classStr = '';
      } ////调用插件


      if (options && Array.isArray(options.plugins)) {
        options.plugins.forEach(function (plugin) {
          if (typeof plugin === 'function') {
            plugin(node);
          }
        });
      } ////调用visitors 


      if (options && options.visitors) {
        var func = options.visitors;

        if (func[node.tag]) {
          func[node.tag](node);
        }
      }
    },
    end: function end(tag) {
      //debug(tag);
      // merge into parent tag
      var node = bufArray.shift();
      if (node.tag !== tag) console.error('invalid state: mismatch end tag'); //当有缓存source资源时于于video补上src资源

      if (node.tag === 'video' && results.source) {
        node.attr.src = results.source;
        delete results.source;
      }

      if (bufArray.length === 0) {
        results.nodes.push(node);
      } else {
        var parent = bufArray[0];

        if (parent.nodes === undefined) {
          parent.nodes = [];
        }

        parent.nodes.push(node);
      }
    },
    chars: function chars(text) {
      //debug(text);
      var node = {
        node: 'text',
        text: text // textArray:transEmojiStr(text)

      };

      if (bufArray.length === 0) {
        node.index = index.toString();
        index += 1;
        results.nodes.push(node);
      } else {
        var parent = bufArray[0];

        if (parent.nodes === undefined) {
          parent.nodes = [];
        }

        node.index = parent.index + '.' + parent.nodes.length;
        parent.nodes.push(node);
      }
    },
    comment: function comment(text) {//debug(text);
      // var node = {
      //     node: 'comment',
      //     text: text,
      // };
      // var parent = bufArray[0];
      // if (parent.nodes === undefined) {
      //     parent.nodes = [];
      // }
      // parent.nodes.push(node);
    }
  });
  return results.nodes;
}
1186521
def get_xml_str(self, data):
        

        responses = []
        for tag, value in data.items():
            elem = Element(tag)
            if isinstance(value, dict):
                for value in self.get_xml_str(value):
                    elem.append(value)
            elif isinstance(value, list):
                value = ', '.join([m for m in value])
                elem.text = value
            else:
                elem.text = value
            responses.append(elem)
        return responses
1358341
function toJSON(node) {
  node = node || this;

  var obj = {
    nodeType: node.nodeType
  };

  if (node.tagName) {
    obj.name = node.tagName.toLowerCase();
  } else if (node.nodeName) {
    obj.name = node.nodeName.toLowerCase();
  }
  if (node.nodeValue) {
    obj.nodeValue = node.nodeValue;
  }
  var attrs = node.attributes;

  if (attrs) {
    var length = attrs.length;

    obj.props = {};
    for (var i = 0; i < length; i++) {
      var attr = attrs[i];

      obj.props[attr.nodeName] = attr.nodeValue;
    }
  }
  var childNodes = node.childNodes;

  if (childNodes) {
    var _length = childNodes.length;

    obj.children = [];
    for (var _i = 0; _i < _length; _i++) {
      obj.children.push(toJSON(childNodes[_i]));
    }
  }
  return obj;
}
213432
function formatToJsonXMLString(changes, shallow) {
            var properties = [];

            var diff = changes.value;
            if (changes.changed == 'equal') {
                return $sce.trustAsHtml(inspect(diff, shallow));
            }

            for (var key in diff) {
                properties.push(formatChange(key, diff[key], shallow));
            }

            return $sce.trustAsHtml('<span>' + openChar + '</span>\n<div class="diff-level">' + properties.join('<span>,</span>\n') + '\n</div><span>' + closeChar + '</span>');

        }
664807
public org.jsoup.nodes.Document getFromHtml(String uri){
        // 取回資料
        String html = getFromRemote(uri);

        // 轉化為 Jsoup 物件
        return htmlToJsoupDoc(html);
    }
326258
function textXml(data) {
                var xml = undefined,
                    tmp = undefined;
                if (!data || typeof data !== "string") {
                    return null;
                }

                // Support: IE9
                try {
                    tmp = new DOMParser();
                    xml = tmp.parseFromString(data, "text/xml");
                } catch (e) {
                    xml = undefined;
                }

                if (!xml || xml.getElementsByTagName("parsererror").length) {
                    throwError("Invalid XML: " + data);
                }
                return xml;
            }
905369
function ( xhr, type ) {
		type = type || "";
		var result, obj;

		if ( ( regex.json_maybe.test( type ) || string.isEmpty( type ) ) && ( regex.json_wrap.test( xhr.responseText ) && Boolean( obj = json.decode( xhr.responseText, true ) ) ) ) {
			result = obj;
		}
		else if ( regex.xml.test( type ) ) {
			if ( type !== "text/xml" ) {
				xhr.overrideMimeType( "text/xml" );
			}

			result = xhr.responseXML;
		}
		else if ( type === "text/plain" && regex.is_xml.test( xhr.responseText) && xml.valid( xhr.responseText ) ) {
			result = xml.decode( xhr.responseText );
		}
		else {
			result = xhr.responseText;
		}

		return result;
	}