2013-04-15 74 views
3

這個問題可能已經在Interwebs的一些黑暗的休息之前得到了回答,但我甚至無法弄清楚如何形成有意義的Google查詢來搜索它。JAXB:獲取標記爲字符串

所以:假設我有一個像(簡體)XML文檔這樣:

<root> 
    <tag1>Value</tag1> 
    <tag2>Word</tag2> 
    <tag3> 
    <something1>Foo</something1> 
    <something2>Bar</something2> 
    <something3>Baz</something3> 
    </tag3> 
</root> 

我知道如何使用JAXB解組此爲Java對象的標準用例。

什麼我不知道該怎麼辦是取消編組tag3的內容批發成一個字符串。我的意思是:

<something1>Foo</something1> 
<something2>Bar</something2> 
<something3>Baz</something3> 

作爲一個字符串,標籤和所有。

+0

在這種情況下,您不是在編組。獲取完整的XML並使用正則表達式或自定義分析來獲取'' –

回答

1

使用註釋@XmlAnyElement。 我一直在尋找相同的解決方案,我期望找到一些註釋,它可以防止解析dom並按原樣生活,但是沒有找到它。

詳細地: Using JAXB to extract inner text of XML elementhttp://blog.bdoughan.com/2011/04/xmlanyelement-and-non-dom-properties.html 我加入方法getElement()一個cheking,否則我們可以得到IndexOutOfBoundsException異常

if (xml.indexOf(START_TAG) < 0) { 
    return ""; 
} 

對於我來說,這個解決方案很奇怪的行爲。方法getElement()會針對xml的每個標記調用。第一個電話是「值」,第二個 - 「ValueWord」等,這對於追加以前

更新下一個標籤: 我注意到,這種方法僅適用於ONE occurence標籤的,我們要解析爲String。這是不可能的分析正確followint例如:

<root> 
<parent1> 
    <tag1>Value</tag1> 
    <tag2>Word</tag2> 
    <tag3> 
     <something1>Foo</something1> 
     <something2>Bar</something2> 
     <something3>Baz</something3> 
    </tag3> 
</parent1> 
<parent2> 
    <tag1>Value</tag1> 
    <tag2>Word</tag2> 
    <tag3> 
     <something1>TheSecondFoo</something1> 
     <something2>TheSecondBar</something2> 
     <something3>TheSecondBaz</something3> 
    </tag3> 
</parent2> 

「標籤3」與父標籤「parent2」將包含來自第一變量參數(美孚,酒吧,巴茲)而不是(TheSecondFoo,TheSecondBar, TheSecondBaz) 任何建議表示讚賞。 謝謝。

+0

我獨立地偶然發現博客文章提出問題後,最終使用該解決方案。考慮到其他答案完全失敗,你會得到綠色的複選標記。 –

-1

我有一個實用的方法,可能會在這種情況下派上用場。看看它是否有幫助。我用你的示例做了一個示例代碼:

public static void main(String[] args){ 
    String text= "<root><tag1>Value</tag1><tag2>Word</tag2><tag3><something1>Foo</something1><something2>Bar</something2><something3>Baz</something3></tag3></root>"; 
    System.out.println(extractTag(text, "<tag3>")); 

} 

public static String extractTag(String xml, String tag) { 
    String value = ""; 
    String endTag = "</" + tag.substring(1); 

    Pattern p = Pattern.compile(tag + "(.*?)" + endTag); 
    Matcher m = p.matcher(xml); 

    if (m.find()) { 
     value = m.group(1); 
    } 

    return value; 
} 
+0

的所有內容爲什麼downvote? –

+0

我想它與這個有關:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 –