在Java中嵌套XML标签时面临的问题

时间:2019-03-14 18:22:39

标签: java xml

我正在尝试用Java创建XML文件,希望得到以下输出:

<Row>
  <customer_name> foo </customer_name>
  <address>
     <street_address> 123 Hemming Way </street_address>
     <city> Brandon </city>
  </address>
  <region> Manitoba </region>
</Row>

我得到的输出没有像这样的<address>标签的嵌套:

<Row>
   <customer_name> foo </customer_name>
   <street_address> 123 Hemming Way </street_address>
   <city> Brandon </city>
   <region> Manitoba </region>
</Row>

我不知道如何为<address>street_address包括city的单独嵌套。 我的代码如下:

ResultSet rs = statement.executeQuery("Select  customer_name,street_address,city, region  from customers ");
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();

while (rs.next()) {
    Element row = doc.createElement("Row");
    results.appendChild(row);
    for (int i = 1; i <= colCount; i++) {
        String columnName = rsmd.getColumnLabel(i);
        Object value = rs.getObject(i);
        Element node = doc.createElement(columnName);
        node.appendChild(doc.createTextNode(value.toString()));
        row.appendChild(node);
    }
}

1 个答案:

答案 0 :(得分:1)

如果只为所有列编写通用循环,则不能。您需要编写更明确的代码,因此street_addresscity嵌套在address标记内。

我建议您消除列循环,并为每列编写特定的代码。

Helper方法可能是一个好主意:

static Element addElement(Element parent, String name) {
    Element elem = parent.getOwnerDocument().createElement(name);
    parent.appendChild(elem);
    return elem;
}

static void addElementValue(Element parent, String name, String value) {
    addElement(parent, name).appendChild(parent.getOwnerDocument().createTextNode(value));
}

现在更容易编写逻辑:

while (rs.next()) {
    Element row = addElement(results, "Row");
    addElementValue(row, "customer_name", rs.getString("customer_name"));
    Element address = addElement(row, "address");
    addElementValue(address, "street_address", rs.getString("street_address"));
    addElementValue(address, "city", rs.getString("city"));
    addElementValue(row, "region", rs.getString("region"));
}

例如,如果您愿意的话,这也使您更容易命名更好的元素

while (rs.next()) {
    Element row = addElement(results, "Customer");
    addElementValue(row, "Name", rs.getString("customer_name"));
    Element address = addElement(row, "Address");
    addElementValue(address, "Street", rs.getString("street_address"));
    addElementValue(address, "City", rs.getString("city"));
    addElementValue(row, "Region", rs.getString("region"));
}

创建以下XML:

<Customer>
    <Name>foo</Name>
    <Address>
        <Street>123 Hemming Way</Street>
        <City>Brandon</City>
    </Address>
    <Region>Manitoba</Region>
</Customer>