2016-11-16 16 views
1

RESTサービスにPOSTを取得した最終的なメッセージのテンプレートであるローカルファイルにXMLがあります。スクリプトは、テンプレートデータが投稿される前にそのデータを事前に処理します。メッセージのXMLがrepeatingElementタグは他の何か(の属性に基づいて、スクリプトによって生成されたXMLを交換する必要があることを除いて同じになるはずですXMLタグをBeautifulSoupで置き換える/削除するには?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<root> 
    <singleElement> 
     <subElementX>XYZ</subElementX> 
    </singleElement> 
    <repeatingElement id="11" name="Joe"/> 
    <repeatingElement id="12" name="Mary"/> 
</root> 

だからテンプレートは、次のようになります既存のタグ)。ここで

は、これまでのところ、私のスクリプトです:

xmlData = None 

with open('conf//test1.xml', 'r') as xmlFile: 
    xmlData = xmlFile.read() 

xmlSoup = BeautifulSoup(xmlData, 'html.parser') 

repElemList = xmlSoup.find_all('repeatingelement') 

for repElem in repElemList: 
    print("Processing repElem...") 
    repElemID = repElem.get('id') 
    repElemName = repElem.get('name') 

    # now I do something with repElemID and repElemName 
    # and no longer need it. I would like to replace it with <somenewtag/> 
    # and dump what is in the soup object back into a string. 
    # is it possible with BeautifulSoup? 

は、私が何か他のものと繰り返しエレメントを交換してから、私は私のREST APIに投稿することができ、新たな文字列にスープのオブジェクトをダンプすることはできますか?

注: I can't get the xml parser to workので、私はhtml.parserを使用していますが、それは大丈夫、理解HTMLはXMLの解析よりも寛容である動作します。

答えて

1

あなたは.replace_with().new_tag()メソッドを使用することができます。

for repElem in repElemList: 
    print("Processing repElem...") 
    repElemID = repElem.get('id') 
    repElemName = repElem.get('name') 

    repElem.replace_with(xmlSoup.new_tag("somenewtag")) 

次に、あなたがstr(soup)soup.prettify()を使用して "スープ" をダンプすることができます。

+0

おかげで、私はちょうど同じ解決策を出しました – amphibient

+0

残念ながら、私のシステム(Win7)で動作する唯一のスープパーサーは 'html.parser'です(xmlはhttp://stackoverflow.com/すべてのタグを小文字に変換し、REST APIは大文字と小文字を区別します(例:40640026/how-to-install-module-for-beautifulsoup-xml-parsing?noredirect = 1#comment68512605_40640026) – amphibient

関連する問題