私はSTAFとSTAXで作業しています。 Pythonはコーディングに使用されます。私はPythonの初心者です。 私の仕事は、Document Factory Parserを使ってPythonでXMLファイルを解析することです。XML文書ビルダーファクトリを使用したPythonでの構文解析
私が解析しようとしているXMLファイルです:私はすべてのタグを読み取る必要が
<?xml version="1.0" encoding="utf-8"?>
<operating_system>
<unix_80sp1>
<tests type="quick_sanity_test">
<prerequisitescript>preparequicksanityscript</prerequisitescript>
<acbuildpath>acbuildpath</acbuildpath>
<testsuitscript>test quick sanity script</testsuitscript>
<testdir>quick sanity dir</testdir>
</tests>
<machine_name>u80sp1_L004</machine_name>
<machine_name>u80sp1_L005</machine_name>
<machine_name>xyz.pxy.dxe.cde</machine_name>
<vmware id="155.35.3.55">144.35.3.90</vmware>
<vmware id="155.35.3.56">144.35.3.91</vmware>
</unix_80sp1>
</operating_system>
- 。
タグmachine_nameについては、リストに読み込む必要があります。 すべてのマシン名がリストmachnameである必要があります。 タグを読み取った後、machnameは[u80sp1_L004、u80sp1_L005、xyz.pxy.dxe.cde]にする必要があります。 すべての属性が= [155.35.3.55,155.35.3.56] すべてのVMwareの値は= [144.35.3.90,155.35.3.56]
私はvmwareタグとマシン名タグ以外のすべてのタグを正しく読むことができます: 私は次のコードを使用しています:(私はxmlとvmwareを初めて使っています)。
以下のコードを変更する必要があります。
factory = DocumentBuilderFactory.newInstance();
factory.setValidating(1)
factory.setIgnoringElementContentWhitespace(0)
builder = factory.newDocumentBuilder()
document = builder.parse(xmlFileName)
vmware_value = None
vmware_attr = None
machname = None
# Get the text value for the element with tag name "vmware"
nodeList = document.getElementsByTagName("vmware")
for i in range(nodeList.getLength()):
node = nodeList.item(i)
if node.getNodeType() == Node.ELEMENT_NODE:
children = node.getChildNodes()
for j in range(children.getLength()):
thisChild = children.item(j)
if (thisChild.getNodeType() == Node.TEXT_NODE):
vmware_value = thisChild.getNodeValue()
vmware_attr ==??? what method to use ?
# Get the text value for the element with tag name "machine_name"
nodeList = document.getElementsByTagName("machine_name")
for i in range(nodeList.getLength()):
node = nodeList.item(i)
if node.getNodeType() == Node.ELEMENT_NODE:
children = node.getChildNodes()
for j in range(children.getLength()):
thisChild = children.item(j)
if (thisChild.getNodeType() == Node.TEXT_NODE):
machname = thisChild.getNodeValue()
タグが存在するかどうかを確認する方法もあります。私は適切に構文解析をコード化する必要があります。
私はスペースがPythonでは重要であることを知っていますので、どのようにコードの壁をフォーマットするのか分かりません。あなたはそれであなた自身の上にいる、OP。 – Welbog