我正在尝试使用DocumentBuilder API在Blackberry应用程序中创建和编写XML。我编写了以下方法来创建至少一个元素及其属性:
private void createResponseXML()
{
try
{
// Build a document based on the XML file.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element surveyElement = document.createElement("Survey");
surveyElement.setAttribute("xmlns:abapsurvey", "http://www.sap.com/abapsurvey");
FileConnection fileConnection = (FileConnection) Connector.open("file:///SDCard/survey_response.xml", Connector.READ_WRITE, true);
OutputStream outputStream = fileConnection.openOutputStream();
XMLWriter writer = new XMLWriter(outputStream);
writer.setPrettyPrint();
DOMInternalRepresentation.parse(document, writer);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
我正在尝试创建的XML结构如下:
<?xml version="1.0" encoding="utf-8" ?>
- <Survey xmlns:abapsurvey="http://www.sap.com/abapsurvey" xmlns:bee="http://www.sap.com/survey/bee" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:htmlb="http://www.sap.com/survey/htmlb" xmlns:out="http://www.w3.org/1999/XSL/Output" xmlns:svy="http://www.sap.com/survey/svy" xmlns:tmp="http://www.sap.com/survey/tmp" xmlns:values="http://www.w3.org/1999/XSL/TransformValues" xmlns:wff="http://www.mysap.com/wff/2001">
- <Values>
- <Question QuestionId="q1">
- <Answer AnswerId="id_4214130a0e731678e10000000a114eea">
<Value>id_4214134d0e731678e10000000a114eea</Value>
</Answer>
</Question>
- <Question QuestionId="id_421413b20e731678e10000000a114eea">
- <Answer AnswerId="id_421413cb0e731678e10000000a114eea">
<Value>id_421413f70e731678e10000000a114eea</Value>
</Answer>
</Question>
- <Question QuestionId="id_4214142c0e731678e10000000a114eea">
- <Answer AnswerId="id_4214143e0e731678e10000000a114eea">
<Value>id_4214f3f6f3eb3d67e10000000a114eea</Value>
</Answer>
</Question>
- <Question QuestionId="id_4214f40cf3eb3d67e10000000a114eea">
- <Answer AnswerId="id_42144d6d48021679e10000000a114eea">
<Value>id_42144d9048021679e10000000a114eea</Value>
</Answer>
</Question>
</Survey>
我在笔记本电脑硬盘上创建了一个文件夹来模拟SD卡。当我调用此方法时,创建的XML只包含如下标题:
<?xml version="1.0"?>
为什么我尝试使用以下代码附加的元素未在XML中创建?
Element surveyElement = document.createElement("Survey");
surveyElement.setAttribute("xmlns:abapsurvey", "http://www.sap.com/abapsurvey");
请建议。
答案 0 :(得分:1)
您可能需要在serverElement.setAttrib
doucment.appendChild(surveyElement);
此语句附加您创建的子元素。