My function receive's XML but it is formatted as a string, I'm attempting to convert this string into XML and the XML into a POJO. The function will only ever receive one object.
Here's what I got:
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:
I guess I'm not reading the object's values correctly, but I'm confused as to why this is the case when the answer given here is no different from my own. Never worked with XML until now
I was able to correct this behaviour by using
.getNodeValue()instead of.getAttributes()