2016-02-03 43 views
1

我一直在嘗試使用這個偉大的example來讀取XML文件,將它們轉換爲GeoJson並最終將它們導入到MongoDB中。使用Groovy將XML轉換爲GeoJson

我的示例XML文件是這樣的:

<AName att1="sequence" att2="xx" att3="xxx"> 
    <Loc1>0</Loc1> 
    <Loc2>0</Loc2> 
</AName> 

<AName att1="sequence" att2="xx" att3="xxx"> 
    <Loc1>3</Loc1> 
    <Loc2>6</Loc2> 
</AName> 

....

而且我GeoJSON的結構實際上應該是這樣的(一個典型的Polygon with a Single Ring):

{ 
    type: "Polygon", 
    name: "sequence", 
    coordinates: [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ] ] 
} 

我已經開始使用Groovy(我以前從未使用過),但我不確定實際的GeoJson創建是否與我的要求相似(我實際上並不認爲它有我rked)。

//Here I am using the XmlSlurper() to parse the xml file 

    def file= new XmlSlurper().parse(new File('MyFile.xml')); 
    def a = file.AName[0][email protected]; 
    println("AName " + a); 
    def loc1= file.depthFirst().find() {it.name() == 'Loc1'}; 
    def loc2= file.depthFirst().find() {it.name() == 'Loc2'}; 

    //Here I am converting the Java representation of my XML file to a GeoJson format 

file.node.each {child -> 
    Map myMap= [type: 'Polygon', 
     name : a, 
     loc: [coordinates: 
       [Double.valueOf(loc1), Double.valueOf(loc2)], 
       ]] 

    //Finally I am inserting the BasicDBObject and creating the 2dsphere index 

    collection.insert(new BasicDBObject(myMap)); 
    collection.createIndex(new BasicDBObject('loc', '2dsphere')); 

雖然該索引已創建,但在我的收藏中看不到記錄。我的代碼中有明顯的錯誤嗎?映射是否遞歸地在我的Polygon中添加座標數組?有沒有更好的故障排除方法? (我目前使用的是mongo-java-driver-3.2.1)

非常感謝您的幫助!

+0

你可以張貼一些實際的XML和JSON實際你希望它可以產生? –

+0

@time_yates,我已經闡明瞭我想實現的GeoJson的類型。希望這可以幫助。 – paranza

+0

但是XML中的座標在哪裏? X屬性在哪裏?您的示例x​​ml發送與期望的輸出沒有任何相似之處,或者代碼 –

回答

1

因此,想出了這個:

import groovy.json.* 

def xml = ''' 
<root> 
<AName att1="sequence" att2="xx" att3="xxx"> 
    <Loc1>0</Loc1> 
    <Loc2>0</Loc2> 
</AName> 

<AName att1="sequence" att2="xx" att3="xxx"> 
    <Loc1>3</Loc1> 
    <Loc2>6</Loc2> 
</AName> 
</root> 
''' 

def doc = new XmlSlurper().parseText(xml) 

def polymap = [ 
    type: 'Polygon', 
    name: doc.AName.head()[email protected](), 
    points: doc.AName.collect { [it.Loc1.text() as Double, it.Loc2.text() as Double] } 
] 

def json = new JsonBuilder(polymap).toString() 

assert json == '{"type":"Polygon","name":"sequence","points":[[0.0,0.0],[3.0,6.0]]}' 

這你想要做什麼(我覺得)

+0

感謝您的這一點,非常感謝您的解決方案確實工作,我只需要用.find()替換.head()。我想知道是否有更好的方法來讀取整個XML。我可以做一些像def file = new XmlSlurper()。parse(new File('C:\\ file.xml')),但是如何解析xml的整個內容?謝謝,我 – paranza

+0

我已經閱讀了前面提到的整個文件,並通過它來建立地理結構,所有作品都很精美。而不是 collection.insert(new BasicDBObject(polymap)); 我只是用 collection.insertOne(new Document(polymap));然後創建2dspehere。 – paranza