0

XmlSlurperでグーグルアトムを解析しようとしています。私のユースケースはこのようなものです。

1)RESTクライアントを使用してAtomxmlをサーバーに送信します。

2)リクエストを処理し、サーバー側で解析します。

Groovyを使用してサーバーを開発し、パーサーとしてXmlSlurperを使用しました。しかし、私は成功せず、「コンテンツはプロローグで許可されていません」という例外を取得できませんでした。そして、私はそれが起こった理由を見つけようとしました。アトムxmlをutf-8でエンコードされたファイルに保存しました。次に、ファイルの読み取りとアトムの解析を試みましたが、同じ例外が発生します。しかし、それから私はatomxmlをファイルに保存しました。whixhはansiでエンコードされています。そして、atomxmlを正常に解析しました。したがって、問題はXmlSlurperと「UTF-8」に関するものだと思います。

この制限について何か考えがありますか?私のアトムxmlはutf-8でなければならないので、どうすればこのアトムxmlを解析できますか?ご協力いただきありがとうございます。

XML:

<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:atom='http://www.w3.org/2005/Atom'
    xmlns:gd='http://schemas.google.com/g/2005'>
  <category scheme='http://schemas.google.com/g/2005#kind'
    term='http://schemas.google.com/contact/2008#contact' />
  <title type='text'>Elizabeth Bennet</title>
  <content type='text'>Notes</content>
  <gd:email rel='http://schemas.google.com/g/2005#work'
    address='liz@gmail.com' />
  <gd:email rel='http://schemas.google.com/g/2005#home'
    address='liz@example.org' />
  <gd:phoneNumber rel='http://schemas.google.com/g/2005#work'
    primary='true'>
    (206)555-1212
  </gd:phoneNumber>
  <gd:phoneNumber rel='http://schemas.google.com/g/2005#home'>
    (206)555-1213
  </gd:phoneNumber>
  <gd:im address='liz@gmail.com'
    protocol='http://schemas.google.com/g/2005#GOOGLE_TALK'
    rel='http://schemas.google.com/g/2005#home' />
  <gd:postalAddress rel='http://schemas.google.com/g/2005#work'
    primary='true'>
    1600 Amphitheatre Pkwy Mountain View
  </gd:postalAddress>
</entry>

ファイルを読み取って解析します:

 String file = "C:\\Documents and Settings\\user\\Desktop\\create.xml";
 String line = "";
 StringBuilder sb = new StringBuilder();
 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
 while ((line = br.readLine()) !=null) {
     sb.append(line);
 }
 System.out.println("sb.toString() = " + sb.toString());

 def xmlf = new XmlSlurper().parseText(sb.toString())
    .declareNamespace(gContact:'http://schemas.google.com/contact/2008',
        gd:'http://schemas.google.com/g/2005')

   println xmlf.title  
4

2 に答える 2

3

試す:

String file = "C:\\Documents and Settings\\user\\Desktop\\create.xml"

def xmlf = new XmlSlurper().parse( new File( file ) ).declareNamespace( 
        gContact:'http://schemas.google.com/contact/2008',
        gd:'http://schemas.google.com/g/2005' )
println xmlf.title  

あなたは長い道のりを進んでいます

于 2011-10-18T12:59:03.157 に答える
1

これが問題です:

BufferedReader br = new BufferedReader(
    new InputStreamReader(new FileInputStream(file)));
while ((line = br.readLine()) !=null) {
    sb.append(line);
}

これは、プラットフォームのデフォルトのエンコーディングでファイルを読み取っています。エンコーディングが間違っていると、データが正しく読み取られなくなります。

あなたがすべきことは、XMLパーサーにそれを処理させることです。データの最初の行に基づいて、エンコーディング自体を検出できる必要があります。

私はよく知らないが、入力ストリームを解析できる(この場合は単にそれを与える)ファイル自体の名前を処理できるXmlSlurperと期待している。FileInputStream

于 2011-10-18T12:56:26.960 に答える