2016-07-28 6 views
3

私は、Webサービス呼び出しから取得したXML応答をJavaオブジェクトに解析する最適な方法を判断しようとしています。 JAXBを使用するのが最も簡単な方法ですが、これを実現するすべての例では、XMLが変換されるJavaの型になるテンプレートのJavaクラスが必要です。 私のXMLはJavaオブジェクトへのXMLの解析

<?xml version="1.0" encoding="utf-8" ?> 
    <entry_list version="1.0"> 
     <entry id="main[1]"> <hw highlight="yes" hindex="1">main</hw> <sound><wav>main0001.wav</wav></sound> <pr>ˈmeɪn</pr> <fl>adjective</fl> <lb>always used before a noun</lb> <def><dt>:most important :<sx>chief</sx> <sx>principal</sx> <vi>the <it>main</it> idea/point</vi> <vi>the <it>main</it> goal/purpose</vi> <vi>Speed is the <it>main</it> advantage of this approach.</vi> <vi>The company's <it>main</it> office is located in New York.</vi> <vi>the novel's <it>main</it> character</vi> <vi>driving down the <it>main</it> road/highway</vi> <vi>the <it>main</it> gate/entrance</vi> <vi>This dish can be served as a <phrase>main course</phrase> or appetizer.</vi> <vi>And now for the <phrase>main event</phrase> of the evening!</vi></dt></def> <uro><ure>main*ly</ure> <fl>adverb</fl> <utxt><vi>The reviews have been <it>mainly</it> [=<it>mostly</it>] positive.</vi> <vi>a plant found <it>mainly</it> [=<it>chiefly</it>] in coastal regions</vi> <vi>I don't like the plan, <it>mainly</it> because I think it's too expensive.</vi> <vi>The problems have been <it>mainly</it> minor ones. [=most of the problems have been minor ones]</vi> <vi>They depend <it>mainly</it> on/upon fish for food.</vi></utxt></uro></entry> 
     <entry id="main[2]"> <hw hindex="2">main</hw> <altpr>ˈmeɪn</altpr> <fl>noun</fl> <in><il>plural</il> <if>mains</if></in> <def><sn>1</sn> <sgram>count</sgram> <dt>:the largest pipe in a system of connected pipes <vi>a gas <it>main</it></vi> <vi>a water <it>main</it></vi></dt> <sn>2</sn> <bnote>the mains</bnote> <ssl>Brit</ssl> <sn>a</sn> <dt>:the system of pipes or wires for electricity, gas, or water <vi>My radio runs either off batteries or off <it>the mains</it>.</vi> <un>often used as <it>mains</it> before another noun <vi>We haven't had any <it>mains</it> water/electricity since the storm.</vi></un></dt> <sn>b</sn> <dt>:the place where electricity, gas, or water enters a building or room <vi>Turn off the water at <it>the mains</it>.</vi></dt></def> <dro><dre>in the main</dre> <def><dt>:in general <un>used to say that a statement is true in most cases or at most times <vi>The workers are <it>in the main</it> very capable. [=most of the workers are very capable]</vi> <vi>The weather has <it>in the main</it> been quite good. [=has been quite good most of the time]</vi></un></dt></def></dro></entry> 
     <entry id="main clause"> <hw>main clause</hw> <fl>noun</fl> <in><il>plural</il> <if>⁓ clauses</if></in> <def><gram>count</gram> <sl>grammar</sl> <dt>:a clause that could be used by itself as a simple sentence but that is part of a larger sentence <ca>called also <cat>independent clause</cat></ca> <dx>compare <dxt>coordinate clause</dxt> <dxt>subordinate clause</dxt></dx></dt></def></entry> 
     <entry id="main drag"> <hw>main drag</hw> <fl>noun</fl> <in><il>plural</il> <if>⁓ drags</if></in> <def><gram>count</gram> <sl>US</sl> <sl>informal</sl> <dt>:the main street in a town or city <vi>A carload of teenagers were cruising down the <it>main drag</it>.</vi></dt></def></entry> 
     <entry id="main line"> <hw>main line</hw> <fl>noun</fl> <in><il>plural</il> <if>⁓ lines</if></in> <def><gram>count</gram> <dt>:an important highway or railroad line</dt></def></entry> 
     <entry id="main man"> <hw>main man</hw> <fl>noun</fl> <in><il>plural</il> <if>⁓ men</if></in> <def><gram>count</gram> <sl>US</sl> <sl>informal</sl> <sn>1</sn> <dt>:someone's best male friend <vi>He's still her <it>main man</it>.</vi></dt> <sn>2</sn> <dt>:the most important or admired man in a group <vi>The team has many good players, but he is clearly the <it>main man</it>.</vi></dt></def></entry> 
     <entry id="main squeeze"> <hw>main squeeze</hw> <fl>noun</fl> <in><il>plural</il> <if>⁓ squeezes</if></in> <def><gram>count</gram> <sl>chiefly US slang</sl> <dt>:someone's main girlfriend, boyfriend, or lover <vi>She's my <it>main squeeze</it>.</vi></dt></def></entry> 
     <entry id="main street"> <hw>main street</hw> <fl>noun</fl> <in><il>plural</il> <if>⁓ streets</if></in> <def><sn>1</sn> <sgram>count</sgram> <dt>:the most important street of a U.S. town where there are many stores, banks, etc. <un>often used as a name <vi>The restaurant is at 257 <it>Main Street</it>.</vi></un></dt> <sn>2</sn> <bnote>Main Street</bnote> <sgram>noncount</sgram> <ssl>US</ssl> <dt><un>used to refer to middle-class people in the U.S. who have traditional beliefs and values <vi>What does <it>Main Street</it> think of this policy?</vi></un></dt></def></entry> 
     <entry id="water main"> <hw>water main</hw> <fl>noun</fl> <in><il>plural</il> <if>⁓ mains</if></in> <def><gram>count</gram> <dt>:a large underground pipe that carries water <vi>The <it>water main</it> burst/broke and flooded the street.</vi></dt></def></entry> 
    </entry_list> 

以下のように私の質問は、私はこれが変換されることをJavaオブジェクトを定義しなければならないのですか?私が恐れているのは、データがXML応答に現時点で追加または削除された場合にどうなるかです。 私はDOMにXMLをロードしようとしましたが、そのようにして歩いてみましたが、againi要素が追加されたり削除されたりするとどうなりますか?
親ノードが特定の値である場合にのみ、ある種の子ノードが必要なので、最も簡単な方法を指すポインタを歓迎します。

+0

あなたはより特異的であり得ますあなたが結果として達成したいと思うように、私は確かにもっとキュレーションされた答えを提出することができます –

+0

@ vtd-xml-author タグのすべてのデータを抽出したい、つまり XXXその兄弟ならばノードには特定の値が含まれています。私はXMLのok(SAXパーサー付き)を歩き、私が必要とするデータを得ることができますが、私はこのコードを維持する人ではないので、 "適切な"方法でやりたいと思います。 – MayoMan

答えて

0

XMLで動作する最も簡単な方法は、オブジェクトにシリアライズすることです:あなたは「主節」タグにのみ興味を持っていた場合

たとえば、あなたのハンドラは、次のようになります。
JAXBで行うことができます。チュートリアルは次のとおりです。mykong
オブジェクトの外観を定義するだけです。

@XmlRootElement(name = "entry_list") 
public class EntryList { 

    @XmlElement(name = "entry") 
    private List<Entry> entities; 

    public List<Entry> getEntities() { 
     return entities; 
    } 
    public void setLastName(List<Entry> entities) { 
     this.entities = entities; 
    } 
} 

public class Entry { 

    @XmlAttribute 
    private String id; 

    @XmlElement 
    private Sound sound 

    etc 
    ... 

    public String getId() { 
     return id; 
    } 
    public void setId(String id) { 
     this.id = id; 
    } 

    public Sound getSound() { 
     return sound; 
    } 
    public void setSound(Sound sound) { 
     this.sound = sound; 
    } 
} 

子要素を持ってすべての要素がクラスでなければならない、それはエントリまたはVIのように複数回を繰り返した場合、それはリストでなければなりません:
は、ここでの例です。私の経験で

+0

他の提案をいただきありがとうございますが、これはこれを行う最も直接的な方法であると思われ、保守性はこの問題に対する私の優先事項です。 – MayoMan

0

POJOとよく呼ばれています。はい、それは良いアイデアです。これは、データをオブジェクトとして表現する方法を定義します。データがない場合、Javaオブジェクトのフィールドはnullになります。したがって、Javaオブジェクトをすべての可能な属性のうちの最大のカバーとして定義する必要があります。

が唯一の選択肢がで手動で自分を解析することであろう(少なくとも私は、ジャクソンがJSONのためにそれを行うことができますXMLわからない知っている)ハッシュマップに追加属性を置くいくつかのライブラリがあるかもしれませんノードの深さ最初のトラバースなど、すべての要素の取得を保証する方法

+0

与えられたXMLでは、Java POJOクラス階層全体を作成する必要があります。これは、XMLがEntryオブジェクトのリストであり、各Entryオブジェクト内にサブ構造があることを意味します。それぞれのクラスを作成する必要はありますか? – MayoMan

+0

私はあなたが異なる構造ごとに1つのクラスを必要と思う。 –

0

SAXパーサを使用できます。この方法の美しさは、高速で低メモリであることを除けば、あなたが必要としない、または必要としないすべてのものを無視することです。あなたが通過するときにあなたが望むタグを捕まえるだけです。

public class MyHandler extends org.xml.sax.helpers.DefaultHandler { 

    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 
     if ("entry".equalsIgnoreCase(localName) && 
       "main clause".equalsIgnoreCase(attributes.getValue("id"))) { 
      // Set a member variable flag 
      // So we know how to process nested tags 
     } 
    } 

    public void endElement(String uri, String localName, String qName) throws SAXException { 
     if ("entry".equalsIgnoreCase(localName)) { 
      // Unset the flag 
     } 
    } 
} 
0

、あなたはそのおそらくより簡単に、非常に複雑なXMLドキュメントに対処する必要があります:あなたは で動作することができますオブジェクトに

  1. より単純な形式に変換し元帥それ

    e

    <XML> 
        <SomeElement> 
         <MoreElements> 
          <EvenMoreElements>text</EvenMoreElements> 
         </MoreElements> 
        </SomeElement> 
    </XML> 
    

    ステップ番号1:Javaオブジェクトへ

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
        <xsl:template match="/"> 
         <SimpleForm><xsl:value-of select="XML/SomeElement/MoreElements/EvenMoreElements/text()"/></SimpleForm> 
        </xsl:template> 
    </xsl:stylesheet> 
    

    ステップ2.元帥独自のSimpleFormのXML、XSLTを使用して、それを簡素化

    そのようにあなたは非常に複雑なXMLを持って言うことができます外部スキーマと内部ロジックの結合が緩やかになります。

0

ここではJAXBが最適な解決策ではないと思います...最高の解決策は、コードのメンテナンス性を犠牲にすることなくコーディングを簡素化できるXPathに基づいています。ナビゲーションはちょうど1 XPATH式で、全体のプログラムは、XPathとVTD-XMLを使用していますについて10+行のコードで、ところで、あなたのXMLの例は、上記の投稿整形式ではありません...

import com.ximpleware.*; 
public class extractExample { 

    public static void main(String[] args) throws VTDException { 
     // TODO Auto-generated method stub 
     VTDGen vg = new VTDGen(); 
     if(!vg.parseFile("d:\\xml\\sample.xml", false)){ 
      return; 
     } 
     VTDNav vn = vg.getNav(); 
     AutoPilot ap = new AutoPilot(vn); 
     ap.selectXPath("/entry_list/entry/hw[following-sibling::fl='value']/text()"); 
     int i=0; 
     while((i=ap.evalXPath())!=-1){ 
      System.out.println(" hw value are "+vn.toNormalizedString(i)); 
     } 
    } 

} 
関連する問題