1

この XML フィードを解析するために DOM パーサーを使用しています: http://loc.grupolusofona.pt/index.php/?format=feed

すべてのタグでパーサーが正常に機能するようになりました。説明タグ内から画像を取得できるアイデアがありません。

フィードの説明タグは次のようになります。

<description><![CDATA[<div class="K2FeedIntroText"><p><img style="margin: 10px;"
alt="joana soares rostos" src="http://loc.grupolusofona.pt/images/stories/varios/joana%20soares%20rostos.jpg"
height="110" width="120" />Quis ser veterinária mas deixou-se seduzir pela magia
de retratar o real. Joana Soares frequenta o primeiro ano do curso de Fotografia
da Lusófona e descreve a sua paixão pelas fotos como «inexplicável».</p>
</div>]]></description>

そして、私は画像リンクを取得したかった:

http://loc.grupolusofona.pt/images/stories/varios/joana%20soares%20rostos.jpg

私のパーサー:

public class XMLParser {

// constructor
public XMLParser() {

}

/**
 * Getting XML from URL making HTTP request
 * @param url string
 * */
public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

/**
 * Getting XML DOM element
 * @param XML string
 * */
public Document getDomElement(String xml){
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

        return doc;
}

/** Getting node value
  * @param elem element
  */
 public final String getElementValue( Node elem ) {

     if( elem != null){
         return elem.getTextContent();
             }


     return "";
 }

 /**
  * Getting node value
  * @param Element node
  * @param key string
  * */
 public String getValue(Element item, String str) {     
        NodeList n = item.getElementsByTagName(str);        
        return this.getElementValue(n.item(0));
    }
}

そして私の主な活動:

public class Noticias extends ListActivity {

// All static variables
static final String URL = "http://loc.grupolusofona.pt/index.php/?format=feed";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DESC = "description";
static final String KEY_LINK = "link";
static final String KEY_PUBDATE = "pubDate";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_noticias);

    ArrayList<HashMap<String, Spanned>> menuItems = new ArrayList<HashMap<String, Spanned>>();

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_ITEM);
    // looping through all item nodes <item>
    for (int i = 0; i < nl.getLength(); i++) {
        // creating new HashMap
        HashMap<String, Spanned> map = new HashMap<String, Spanned>();
        Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
        map.put(KEY_ID, Html.fromHtml(parser.getValue(e, KEY_ID)));
        map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
        map.put(KEY_DESC, Html.fromHtml(parser.getValue(e, KEY_DESC)));
        map.put(KEY_PUBDATE, Html.fromHtml(parser.getValue(e, KEY_PUBDATE)));
        map.put(KEY_LINK, Html.fromHtml(parser.getValue(e, KEY_LINK)));

        // adding HashList to ArrayList
        menuItems.add(map);
    }

    // Adding menuItems to ListView
    ListAdapter adapter = new SimpleAdapter(this, menuItems,
            R.layout.linha_feed,
            new String[] { KEY_TITLE, KEY_DESC, KEY_PUBDATE, KEY_LINK }, new int[] {
                    R.id.title, R.id.desc, R.id.pub, R.id.link});

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem

            String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
            String description = ((TextView) view.findViewById(R.id.desc)).getText().toString();
            String pub = ((TextView) view.findViewById(R.id.pub)).getText().toString();
            String link = ((TextView) view.findViewById(R.id.link)).getText().toString();

            // Starting new intent

            System.out.println("Title: " + title);
            System.out.println("Link: " + link);
            System.out.println("Description:" + description);
            System.out.println("Pubdate: " + pub);

            Intent in = new Intent(Intent.ACTION_VIEW);
            in.setData(Uri.parse(link));

            startActivity(in);

        }
    });
}
}

何か案は ?

御時間ありがとうございます。

4

1 に答える 1

1

RegEx次のような単純なパターンで使用します。

<\s*img\s*[^>]+src\s*=\s*(['"]?)(.*?)\1

ここでは、次の関数を使用します。

public static String getMatch(String patternString, String text, int groupIndex){
    Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE | Pattern.DOTALL );
    return RegEx.getMatch(pattern, text, groupIndex);
}

public static String getMatch(Pattern pattern, String text, int groupIndex){
    if(text!=null){
        Matcher matcher = pattern.matcher(text);
        String match = null;
        while(matcher.find()){
            match = matcher.group(groupIndex);
            break;
        }
        return match;           
    }else{
        return null;
    }
}

次に、次のようにそのパターンをプラグインできます。

String imageSource = getMatch("<\\s*img\\s*[^>]+src\\s*=\\s*(['\"]?)(.*?)\\1", description, 2);
于 2012-11-04T05:32:05.013 に答える