我想使用 Java 或 Scala 将 XML 转换为 JSON。下面是工作代码,但在这里我看不到 Json 中 XML 属性的任何标识符来区分它与元素。 我需要帮助来获取 Json 输出中带有标识符 (@) 的 XML 属性。
输入 XML:
<Test>
<AttrTest Code="199" Pro="Intel" Version="9.106">
<Info>FD2F</Info>
</AttrTest>
</Test>
代码:
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))
输出:
{"Test": {"AttrTest": {
"Version": 9.106,
"Pro": "Intel",
"Info": "FD2F",
"Code": 199
}}}
预期输出:
{"Test": {"AttrTest": {
"@Version": 9.106,
"@Pro": "Intel",
"Info": "FD2F",
"@Code": 199
}}}
请帮忙。
最佳答案
恐怕您正在使用的库无法实现这一点。以下是他们的文档:
Some information may be lost in this transformation because JSON is a data format and XML is a document format. XML uses elements, attributes, and content text, while JSON uses unordered collections of name/value pairs and arrays of values. JSON does not does not like to distinguish between elements and attributes.
您可以尝试查看其他 XML->JSON 库或实现预转换步骤,例如,向每个节点的属性附加“@”前缀。
关于Java/Scala - 将 xml 转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62194982/