[英]Java/Scala - Convert xml to json
I want to convert XML to JSON using either Java or Scala.我想使用 Java 或 Z3012DCFF1477E1CBBFEAAB8176458 将 XML 转换为 JSON。 Below is the working code, but here I am not able to see any identifier for XML attributes in Json to differentiate it with elements.下面是工作代码,但在这里我看不到 Json 中 XML 属性的任何标识符,以区分它与元素。 I need help to get XML attributes with identifier(@) in Json output.我需要帮助才能在 Json output 中获取带有标识符(@)的 XML 属性。
Input XML:输入 XML:
<Test>
<AttrTest Code="199" Pro="Intel" Version="9.106">
<Info>FD2F</Info>
</AttrTest>
</Test>
Code:代码:
import org.json.XML
def xmlToJson(xml: String) = {
var PRETTY_PRINT_INDENT_FACTOR = 4
try {
val xmlJSONObj = XML.toJSONObject(xml)
val jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR)
jsonPrettyPrintString
} catch {
case ex: Exception =>
println(ex.toString)
}
}
val xmlStr = "<Test>\n\t\t<AttrTest Code=\"199\" Pro=\"Intel\" Version=\"9.106\">\n\t\t<Info>FD2F</Info>\n</AttrTest>\n</Test>\n\t"
println(xmlToJson(xmlStr))
Output: Output:
{"Test": {"AttrTest": {
"Version": 9.106,
"Pro": "Intel",
"Info": "FD2F",
"Code": 199
}}}
Expected Output:预期 Output:
{"Test": {"AttrTest": {
"@Version": 9.106,
"@Pro": "Intel",
"Info": "FD2F",
"@Code": 199
}}}
Please help.请帮忙。
I am afraid it is not possible with the library you are using.恐怕您正在使用的库是不可能的。 Here's from their docs:以下是他们的文档:
Some information may be lost in this transformation because JSON is a data format and XML is a document format.在此转换中可能会丢失一些信息,因为 JSON 是一种数据格式,而 XML 是一种文档格式。 XML uses elements, attributes, and content text, while JSON uses unordered collections of name/value pairs and arrays of values. XML 使用元素、属性和内容文本,而 JSON 使用名称/值对的无序 collections 和值对的 ZA3CCBC4F5D0CE2DF2C1956。 JSON does not does not like to distinguish between elements and attributes. JSON 不喜欢区分元素和属性。
You may try looking into other XML->JSON libraries or implement a pre-conversion step that would, say, append a "@" prefix to each node's attribute.您可以尝试查看其他 XML->JSON 库或实施预转换步骤,例如 append 每个节点属性的“@”前缀。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.