【问题标题】:Converting XML String to POJO leads to no attributes?将 XML 字符串转换为 POJO 导致没有属性?
【发布时间】:2021-12-13 22:43:42
【问题描述】:

我的函数接收 XML,但它被格式化为字符串,我正在尝试将此字符串转换为 XML 并将 XML 转换为 POJO。该函数只会接收一个对象。

这是我得到的:

String xmlString = "<object><attributeOne>test</attributeOne><attributeTwo>test2</attributeTwo></object>";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

Document xmlObject = builder.parse(new InputSource(new StringReader(xmlString)));

// print root element name
System.out.println("Root element: " + xmlObject.getDocumentElement().getNodeName());

int numRootElements = xmlObject.getDocumentElement().getAttributes().getLength();
System.out.println("Number of attributes: " + String.valueOf(numRootElements));

// log root element attributes:
System.out.println("Root element attributes: ");
for (int i = 0; i < xmlObject.getDocumentElement().getAttributes().getLength(); i++) {               
    System.out.println(xmlObject.getDocumentElement().getAttributes().item(i).getNodeName() 
    + ": "
    + xmlObject.getDocumentElement().getAttributes().item(i).getNodeValue());
}

// Output:
// Root element: object
// Number of attributes: 0
// Root element attributes: 

我想我没有正确读取对象的值,但是当here 给出的答案与我自己的答案没有什么不同时,我很困惑为什么会出现这种情况。直到现在都没有使用过 XML

【问题讨论】:

  • 是否可以选择使用诸如 Jackson 之类的库?
  • 试图使用纯 Java,结果我可以将属性读取为节点
  • 这实际上是什么意思?你的问题现在解决了吗?
  • 是的。因此,我没有使用 .getAttributes(),而是使用了 .getNodeValue()
  • 太棒了。然后考虑将解决方案添加为答案并接受它为正确的。谢谢!

标签: java xml xml-parsing


【解决方案1】:

我能够通过使用 .getNodeValue() 而不是 .getAttributes() 来纠正这种行为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多