带有XML SAX getValues()的Null控件

2024-03-29 10:37:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解析以下xml文件:

    <?xml version="1.0" encoding="UTF-8"?>
<gexf xmlns="http://www.gexf.net/1.2draft" version="1.2">
    <graph mode="static" defaultedgetype="directed">
        <nodes>
            <node id="0" label="Hello" />
            <node id="1" label="Word" />
        <node id="2" /> 
        </nodes>
        <edges>
            <edge id="0" source="0" target="1" />
        <edge id="1" source="1" target="2" weight="2.0" />
        </edges>
    </graph>
</gexf>

可以看到,有些边有权重,有些没有。你知道吗

我的代码如下:

elif name == "edge":
        u = attrs.getValue("source")
        v = attrs.getValue("target")
        w = attrs.getValue("weight")
        if w is not None:
            self.edgeweight = w

在这里,我期望w在XML文件的第一行是None,在第二行是2.0。相反,我得到的只是一个错误。怎样才能控制这一切?你知道吗


Tags: 文件idnodesourcetargetversionxmlattrs
2条回答

请尝试以下操作。你知道吗

if attrs.hasKey("weight"):
    w = attrs.getValue("weight")
    self.edgeweight = w

我使用this作为参考。它没有指定您是否可以使用"weight" in attrs,但是您可以尝试看看它是否有效。你知道吗

get()方法成功了。你知道吗

w = attrs.get("weight")
            if w is not None:
                self.weighted = True
                self.edgeweight = float(w)

相关问题 更多 >