0

我正在使用 SAX 解析 xml 文件,但无法获得“y”的值

这是xml,

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type= "text/html" ?>
<Chart1 count="3">
            <Sales_x0020_Amount Label="Sales Amount">
               <Chart1_CategoryGroup_Collection>
                  <Chart1_CategoryGroup Label="URC 1">
                     <Value Y="30434929.1" />
                     <name>keeevin</name>
                  </Chart1_CategoryGroup>
                  <Chart1_CategoryGroup Label="URC 2">
                     <Value Y="39757503.83" />
                     <name>kevin2</name>
                  </Chart1_CategoryGroup>
                  <Chart1_CategoryGroup Label="URC 3">
                     <Value Y="19611069.73" />
                     <name>kevin</name>
                  </Chart1_CategoryGroup>
               </Chart1_CategoryGroup_Collection>
            </Sales_x0020_Amount>
</Chart1>

我可以得到属性“name”的值,但不能得到“y”的值。

获取值的部分代码..

Element e = (Element)nodes.item(i);
map.put("Name", "Name:" + XMLfunctions.getValue(e, "name"));
map.put("Y", "Y Coord:" + XMLfunctions.getValue(ee, "y"));

谢谢。

编辑:我在这里设置了一个断点,它不会通过这里。

static class MyHandler extends DefaultHandler {
    public void startElement(String namespaceURI, String localName,
                             String qName, Attributes atts)  {
        // Get the number of attribute
        int length = atts.getLength();

    // Process each attribute
    for (int i=0; i<length; i++) {
        // Get names and values for each attribute
        String name = atts.getQName(i);
        String value = atts.getValue(i);
        if(qName == "Value"){
             y = atts.getValue(i);
        }
        String nsUri = atts.getURI(i);
        String lName = atts.getLocalName(i);
    }
}

}

使用这个解决了它:

    public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {

            elementOn = true;

    if (localName.equals("Chart"))
            {
                data = new XMLGettersSetters();
            }
            if (qName.equals("Value")) {
                String attributeValue = attributes.getValue(0);
                data.setValue(attributeValue);
            }
}
4

2 回答 2

1

您的起始元素将是图表,该计数将是属性,它将出现在 if 部分中,而不是在 else if 部分中,Sales_x0020_Amount 将出现,并且该属性将是标签。参考本教程

于 2013-10-28T11:15:50.927 回答
0

在您的 Handler(extended DefaultHandler) 中的 startElement 方法中写入

public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {
    if (qName.equals("Value")) {
                 map.put("Y", "Y Coord:" + attributes.getValue(0));
            }
    }
于 2013-04-02T07:44:02.287 回答