2017-03-09 54 views
1

我在xml中獲得應該轉換爲「xml:lang」的屬性「lang」,其他元素和屬性保持不變,並且還將DOCTYPE標記添加爲第二行。我需要使用SAP HANA集成平臺中的代碼。在groovy或Java腳本中將屬性lang轉換爲xml:lang

請幫我分享Groovy或JavaScript代碼以達到上述目的。

例如:輸入

<?xml version="1.0" encoding="UTF-8"?> 
    <root> 
    <Description lang="en">TEST</Description> 
    <Forecast> 
    <Period endDate="2016-09-01T23:59:59+02:00" startDate="2016-09-01T00:00:00+02:00"/> 
    <ForecastQuantity quantity="34.0"> 
    <name lang="en">TEST1</name> 
    <UnitOfMeasure>EA</UnitOfMeasure> 
    </ForecastQuantity> 
    </Forecast> 
    </root> 

輸出應該是:

<?xml version="1.0" encoding="UTF-8"?> 
    <!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.029/cXML.dtd"> 
    <root> 
    <Description xml:lang="en">TEST</Description> 
    <Forecast> 
    <Period endDate="2016-09-01T23:59:59+02:00" startDate="2016-09-01T00:00:00+02:00"/> 
    <ForecastQuantity quantity="34.0"> 
    <name xml:lang="en">TEST1</name> 
    <UnitOfMeasure>EA</UnitOfMeasure> 
    </ForecastQuantity> 
    </Forecast> 
    </root> 

感謝

回答

1

您可以更改屬性名稱,如:

def startXml = """<?xml version="1.0" encoding="UTF-8"?> 
<root> 
<Description lang="en">TEST</Description> 
<Forecast> 
<Period endDate="2016-09-01T23:59:59+02:00" startDate="2016-09-01T00:00:00+02:00"/> 
<ForecastQuantity quantity="34.0"> 
<name lang="en">TEST1</name> 
<UnitOfMeasure>EA</UnitOfMeasure> 
</ForecastQuantity> 
</Forecast> 
</root>""" 

def parser = new XmlParser() 
def root = parser.parseText(startXml) 
root.Forecast.ForecastQuantity.name[0].replaceNode{ 
name('xml:lang': [email protected][0], 
    root.Forecast.ForecastQuantity.name[0].value()) 
} 

println XmlUtil.serialize(root) 

主要生產

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <Description lang="en">TEST</Description> 
    <Forecast> 
    <Period endDate="2016-09-01T23:59:59+02:00" startDate="2016-09-01T00:00:00+02:00"/> 
    <ForecastQuantity quantity="34.0"> 
     <name xml:lang="en">TEST1</name> 
    <UnitOfMeasure>EA</UnitOfMeasure> 
    </ForecastQuantity> 
    </Forecast> 
</root> 
+0

獲取錯誤> groovy.lang.MissingMethodException:方法的無簽名:)java.util.ArrayList.replaceNode(適用於參數類型:(SCRIPT1 $ _run_closure1)值:[SCRIPT1 $ _run_closure1 @ 25b31d24] 在Script1.run(Script1.groovy:15)\t(Script1.groovy:15) – Rao

+0

我使用https://groovyconsole.appspot.com/得到相同的錯誤,但工作正常,運行在intellij中使用2.4.6的腳本 –