2012-05-07 3 views
3

を使用して、XML文書内の文字列を解析:は、次のドキュメント内のAnt

私は値を戻すにはどうすればよい
<?xml version="1.0" encoding="utf-8"?> 
<resources> 
<string name="toc">section</string> 
<string name="id">id17</string> 
</resources> 

:ID17

私はAntのファイルに次のターゲットを実行すると:

<target name="print" 
    description="print the contents of the config.xml file in various ways" > 

    <xmlproperty file="$config.xml" prefix="build"/> 
    <echo message="name = ${build.resources.string}"/> 
    </target> 

私が取得 -

print: 
     [echo] name = section,id17 

リソース "id"だけを指定する方法はありますか?

答えて

4

私には良いニュースと悪い知らせがありました。悪いニュースは、すぐに使える解決策がないということです。良い知らせは、processNode()メソッドをprotectedとして公開すると、xmlpropertyタスクがかなり拡張可能であることです。ここで何ができるかです:今

package pl.sobczyk.piotr; 

import org.apache.tools.ant.taskdefs.XmlProperty; 
import org.w3c.dom.NamedNodeMap; 
import org.w3c.dom.Node; 

public class MyXmlProp extends XmlProperty{ 

@Override 
public Object processNode(Node node, String prefix, Object container) { 
    if(node.hasAttributes()){ 
     NamedNodeMap nodeAttributes = node.getAttributes(); 
     Node nameNode = nodeAttributes.getNamedItem("name"); 
     if(nameNode != null){ 
      String name = nameNode.getNodeValue(); 

      String value = node.getTextContent(); 
      if(!value.trim().isEmpty()){ 
       String propName = prefix + "[" + name + "]"; 
       getProject().setProperty(propName, value); 
      } 
     } 
    } 

    return super.processNode(node, prefix, container); 
} 

} 

2:

1.クラスパス上の(あなたが蟻の分布やget it from Mavenlibサブディレクトリ内の1つを見つけることができます)、次のコードを作成し、ant.jarを使用してコンパイルこのタスクをantに見えるようにする必要があります。最も簡単な方法は、taskサブディレクトリをあなたのantスクリプトを作成する場所に作成します.->コンパイルされたMyXmlPropクラスをディレクトリ構造taskにコピーします。task/pl/sobczyk/peter/MyXmlProp.classのようになります。 Antスクリプトに

3.インポートタスクは、あなたのようなもので終わる必要があります。

<target name="print"> 
    <taskdef name="myxmlproperty" classname="pl.sobczyk.piotr.MyXmlProp"> 
    <classpath> 
     <pathelement location="task"/> 
    </classpath> 
    </taskdef> 
    <myxmlproperty file="config.xml" prefix="build"/> 
    <echo message="name = ${build.resources.string[id]}"/> 
</target> 

4.ファイル名を指定して実行アリ、アリほら、あなたが表示されるはずです。[echo] name = id17

私たちはここにいた何ですかあなたの特定のケースのための特別なファンシー角括弧の構文を定義します:-)。より一般的な解決策のために、タスクの拡張は少し複雑かもしれませんが、すべてが可能です:)。がんばろう。

+0

詳細な対応をありがとうございます。私は結果を公表します。 – VARoadstter

+0

まさに私が探していたもの! :) – splash

関連する問題