ロゴ メインコンテンツへ
RSSフィード
「ソフトウェア開発」に関連する記事一覧

Python Reading XML by DOM

2011/04/08
(この記事の文字数: 1028)
PythonでDOM(Document Object Model)を使ってXMLファイルからデータを読み込む例です。この例ではJava, C++, Pythonのそれぞれのprint関数をリストアップします。

This is example code for reading XML by DOM(Document Object Model) in Python. In this example, it list up print function in Java, C++ and Python for each rule.
 
Reading XML in Python is very easy!
 
 
sample.xml

<?xml version="1.0" encoding="UTF-8"?>


<CommandList>
  <cmd type="Java">System.out.print("test")</cmd>
  <cmd type="C++">printf("test")</cmd>
  <cmd type="Python">print("test")</cmd>
</CommandList>


source code.

from xml.dom.minidom import parse



def printCommandList(xmlPath):
  dom = parse(xmlPath);
  root = dom.documentElement
  print(root.nodeName);
   
  cmdNodeList = root.childNodes;
  for cmdNode in cmdNodeList:
    if cmdNode.nodeName == "cmd":
      typeName = cmdNode.getAttributeNode("type");
      command = "";
      cmdText = cmdNode.childNodes[0];
      if cmdText.nodeType == cmdText.TEXT_NODE:
        command = cmdText.data;
      print(str(typeName.nodeValue)+":"+str(command));
       
  dom.unlink();
printCommandList("./sample.xml");


output
CommandList
Java: System.out.print("test")
C++: printf("test")
Python: print("test")
 

Reference
DOM(Python版)入門

  このエントリーをはてなブックマークに追加  

<<「ソフトウェア開発」の記事一覧に戻る

「ソフトウェア開発」の前の記事 >>

コメント(0 件)



コンテンツロード: 0.0087 sec
Copyright(C)2006-2024 puarts All Rights Reserved