【问题标题】:Convert a String to a xml Element java将字符串转换为 xml 元素 java
【发布时间】:2013-04-03 13:06:08
【问题描述】:

我想将字符串转换为org.jdom.Element

String s = "<rdf:Description rdf:about=\"http://dbpedia.org/resource/Barack_Obama\">";

我该怎么做?

【问题讨论】:

  • 你已经尝试了什么?
  • 通常,我用root创建一个文档...

标签: java xml


【解决方案1】:

从字符串解析 XML 的方法不止一种:

Example 1:

  String xml = "Your XML";
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));     

Example 2:

使用可以读取输入源的 SAXParser:

 SAXParserFactory factory = SAXParserFactory.newInstance();
 SAXParser saxParser = factory.newSAXParser();
 DefaultHandler handler = new DefaultHandler() {
 saxParser.parse(new InputSource(new StringReader("Your XML")), handler);    

见:SAXParserInputSource

【讨论】:

  • 不,它不起作用,因为这个指令只设置元素的名称。
  • @Abu 为什么要这样评论?
  • @pseudo2188 它从字符串中返回一个 org.jdom.Element 你期望的输出是什么?
  • 我认为,OP 想要解析包含在字符串中的整个 XML 文档。
  • 不是整个文档,在我的输入中,我有一个字符串,但是这个字符串对应一个 XML 元素,我必须将它与其他真正是 XML 元素的变量进行比较,所以我必须转换第一个
【解决方案2】:

我建议您使用来自http://simple.sourceforge.net/.With 的简单 XML 框架,您可以轻松地序列化和反序列化您的对象。我希望这些信息对您很重要。

【讨论】:

    【解决方案3】:
    1. 从您的字符串创建一个Document。查看 JDOM 常见问题解答:How do I construct a Document from a String?
    2. 使用方法Document.getRootElement() 访问根元素。

    (您提到了包 org.jdom,所以我假设您使用 JDOM 1.1。)

    【讨论】:

    • 我通常这样做,但对于我的例子来说,没有必要,因为我必须声明我使用的命名空间,并构造一个有效的 XML
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2012-12-02
    • 2015-01-13
    相关资源
    最近更新 更多