- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 xml 文件
<?xml version="1.0" encoding="utf-8"?>
<sections>
<section>
<name>Most Pouplar</name>
<items>
<item pos="1">
<name>
AcaiBerry Diet
</name>
<description>
<![CDATA[
Natrol AcaiBerry Diet supports weight loss goals when combined with a healthy reduced-calorie diet and exercise program. Acai is a wild fruit harvested in the rain forests of Brazil recognized for its high ORAC (oxygen-radical absorbance capacity) value - a measure of its antioxidant capacity. An adequate intake of antioxidants helps neutralize harmful free radicals that are produced by the body as a result of regular exercise.
]]>
</description>
</item>
<item pos="2">
<name>
AcaiBerry Weekend Cleanse
</name>
<description>
<![CDATA[
AcaiBerry Weekend Cleanse is a 3-step, easy-to-use cleansing program. Step 1 helps minimize occasional constipation/bloating, step 2 helps reduce toxins via antioxidant protection & cell regeneration and step 3 helps to restore the friendly bacteria that protect & strengthen the GI tract.
]]>
</description>
</item>
<item pos="4">
<name>
Carb Intercept Phase 2 + Chromium
</name>
<description>
<![CDATA[
Natrol Carb Intercept supports a low-carb lifestyle by controlling carbohydrates found in breads, cereals, rice, pasta and other starch-containing foods. Each serving provides 1,000mg of Phase 2 Carb Controller; a clinically tested ingredient that inhibits the enzyme responsible for digesting starch into simple sugars your body can absorb.
]]>
</description>
</item>
<item pos="3">
<name>
Resveratrol Diet
</name>
<description>
<![CDATA[
Losing weight has never been so rejuvenating! Natrol introduces Resveratrol Diet, a complex blend of antioxidants, enzymes and other nutrientsto help boost your metabolism and promote calorie burning.
]]>
</description>
</item>
</items>
</section>
<section>
<name>Least Popular</name>
<items>
<item pos="1">
<name>
Advanced Sleep Melatonin 10mg Maximum Strength
</name>
<description>
<![CDATA[
Getting a good night's sleep is even easier with Natrol Melatonin - a natural nightcap. A hormone found in the body, melatonin, helps promote more restful sleep. Natrol Melatonin provides relief for occasional sleeplessness, and helps promote a more relaxing night and better overall health.
]]>
</description>
</item>
<item pos="2">
<name>
Sleep 'N Restore
</name>
<description>
<![CDATA[
If you need to feel more rested due to lack of sleep, try Natrol Sleep 'N Restore. Sleep 'N Restore helps promote a more restful, deeper sleep, while supporting your body's natural restoration processes.* A combination of melatonin and valerian, this natural sleep aide includes antioxidants that can help your body protect its cells from damage to help you restore and recharge while you sleep.
]]>
</description>
</item>
</items>
</section>
</sections>
我将 POJO 定义为
public class ItemPojo {
//Fields of an item
private String itemName;
private String itemDescription;
private int itemPosition;
//Getters and Setters
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public int getItemPosition() {
return itemPosition;
}
public void setItemPosition(int itemPosition) {
this.itemPosition = itemPosition;
}
}
我正在实现一种解析 xml 文件的方法,但我不知道如何读取多个 <item>
标签,位于 <items>
范围内标签。
已编辑
我正在尝试放置部分代码
//Store all items with a particular section
ArrayList<ItemPojo> itemList = new ArrayList<ItemPojo>();
//Store all items categorized by section
Map<String, ArrayList<ItemPojo>> itemStore = new HashMap<String, ArrayList<ItemPojo>>(1);
//Single item
ItemPojo currentItem = null;
//Current section name
String sectionName = null;
public AndroidSaxFeedParser() {
super();
}
public void parse() { //Map<String, ArrayList<ItemPojo>>
RootElement root = new RootElement(SECTIONS);
Element section = root.getChild(SECTION);
Element itemHeader = section.getChild(ITEM_HEADER);
//Read <name> tag as used as section
itemHeader.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
sectionName = body;
}
});
//TODO set item header here
Element items = section.getChild(ITEMS);
Element item = items.getChild(ITEM);
/*//Put all items of same category
items.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
//sort item with position
Collections.sort(itemList, ItemPojo.COMPARE_BY_POSITION);
//Putting it into master list
itemStore.put(sectionName, itemList);
//And clear the item list
itemList.clear();
}
});*/
item.setStartElementListener(new StartElementListener() {
public void start(Attributes attributes) {
currentItem = new ItemPojo();
Log.i("Test xml", "item initalised " + currentItem.toString());
}
});
item.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
// TODO Auto-generated method stub
itemList.add(currentItem);
Log.i("Test xml", "New items found " + currentItem.toString());
}
});
item.getChild(ITEM_NAME).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentItem.setItemName(body);
}
});
item.getChild(DESCRIPTION).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentItem.setItemDescription(body);
}
});
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
//return itemStore;
}
现在我遇到了异常
06-30 12:40:45.312: ERROR/AndroidRuntime(315): Uncaught handler: thread main exiting due to uncaught exception
06-30 12:40:45.342: ERROR/AndroidRuntime(315): java.lang.IllegalStateException: This element already has an end text element listener. It cannot have children.
06-30 12:40:45.342: ERROR/AndroidRuntime(315): at android.sax.Element.getChild(Element.java:68)
06-30 12:40:45.342: ERROR/AndroidRuntime(315): at android.sax.Element.getChild(Element.java:60)
06-30 12:40:45.342: ERROR/AndroidRuntime(315): at org.us.ssg.AndroidSaxFeedParser.parse(AndroidSaxFeedParser.java:82)
06-30 12:40:45.342: ERROR/AndroidRuntime(315): at org.us.ssg.DesTestDemoActivity.checkXml(DesTestDemoActivity.java:109)
06-30 12:40:45.342: ERROR/AndroidRuntime(315): at org.us.ssg.DesTestDemoActivity.onClick(DesTestDemoActivity.java:81)
06-30 12:40:45.342: ERROR/AndroidRuntime(315): at android.view.View.performClick(View.java:2364)
06-30 12:40:45.342: ERROR/AndroidRuntime(315): at android.view.View.onTouchEvent(View.java:4179)
06-30 12:40:45.342: ERROR/AndroidRuntime(315): at android.widget.TextView.onTouchEvent(TextView.java:6541)
我需要什么
我需要阅读所有项目(包括位置、名称和描述)和部分。我正在使用一个 HashMap,作为我放置节的键,作为该键的值,我放置与该特定键(作为节名称)相关的所有项目(带有位置、名称、描述)的 ArrayList。
最佳答案
你一切顺利。下一步是:
为您的项目元素定义一个 startElementListener。像这样:
item.setStartElementListener(new StartElementListener() { @Override public void start(Attributes attributes) { myPojoItem = new PojoItem(); } });
Define a endElementListener for you item element:Like this:
item.setEndElementListener(new EndElementListener() { @Override public void end() { itemList.add(myPojoItem); } });
For each of the children of item do something like the following:
itemName.setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { myPojoItem.setName(body); } });
finish with:
try { Xml.parse(myXmlAsFileInputStream, Xml.Encoding.UTF_8, root.getContentHandler()); } catch (Exception e) { e.printStackTrace(); }
Update: In response to comment by OP, here is how to access attributes of elements:
item.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attributes) {
position = attributes.getValue("pos");
}
});
最终解决方案
来自OP:我已经用这些方式完成了
AndroidSaxFeedParser.java
.
public class AndroidSaxFeedParser extends BaseFeedParser {
//Store all items with a particular section
ArrayList<ItemPojo> itemList = new ArrayList<ItemPojo>();
//Store all items categorized by section
Map<String, ArrayList<ItemPojo>> itemStore = new HashMap<String, ArrayList<ItemPojo>>(1);
//Single item
ItemPojo currentItem = null;
//Current section name
String sectionName = null;
public AndroidSaxFeedParser() {
super();
}
public Map<String, ArrayList<ItemPojo>> parse() {
RootElement root = new RootElement(SECTIONS);
Element section = root.getChild(SECTION);
Element itemHeader = section.getChild(ITEM_HEADER);
//Read <name> tag as used as section
itemHeader.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
sectionName = body.trim();
Log.i("New Section", "New section found : " + sectionName);
}
});
section.setStartElementListener(new StartElementListener() {
public void start(Attributes attributes) {
//Clear the item list
itemList = new ArrayList<ItemPojo>(0);
Log.i("Size of list", "Size : " +itemList.size());
}
});
section.setEndElementListener(new EndElementListener() {
public void end() {
//Putting it into master list
itemStore.put(sectionName, itemList);
}
});
Element items = section.getChild(ITEMS);
Element item = items.getChild(ITEM);
items.setEndElementListener(new EndElementListener() {
public void end() {
//sort item with position
Collections.sort(itemList, ItemPojo.COMPARE_BY_POSITION);
}
});
item.setStartElementListener(new StartElementListener() {
public void start(Attributes attributes) {
currentItem = new ItemPojo();
currentItem.setItemPosition(Integer.parseInt(attributes.getValue("pos")));
//Log.i("Test xml", "item initalised " + currentItem.toString());
}
});
item.setEndElementListener(new EndElementListener() {
public void end() {
itemList.add(currentItem);
Log.i("Test xml", "New items found " + currentItem.toString());
}
});
item.getChild(ITEM_NAME).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentItem.setItemName(body.trim());
}
});
item.getChild(DESCRIPTION).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentItem.setItemDescription(body.trim());
}
});
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
return itemStore;
}
}
.
public abstract class BaseFeedParser implements FeedParser {
// names of the XML tags
static final String SECTIONS = "sections";
static final String SECTION = "section";
static final String ITEM_HEADER = "name";
static final String DESCRIPTION = "description";
static final String ITEM_NAME = "name";
static final String ITEM_POSITION = "pos";
static final String ITEM = "item";
static final String ITEMS = "items";
public InputStream inStream;
public BaseFeedParser() {
//super();
}
protected InputStream getInputStream() {
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(DesTestDemoActivity.INDEX_URL);
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("request_for", "xml_data"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null)
inStream = entity.getContent();
return inStream;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
.
public interface FeedParser {
Map<String, ArrayList<ItemPojo>> parse();
}
在你们的帮助下我已经完成了。谢谢大家。
关于java - android中使用android.sax解析XML问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6517737/
我一直在尝试为 SAX 解析器设置 UI 线程和处理程序。这是我没有实现 UI 线程和处理程序的解析器: public class AndroidXMLReader extends ListActiv
我正在尝试读取一个大型 XML 文档,并且我想以 block 的形式读取它,而不是 XmlDocument 将整个文件读入内存的方式。我知道我可以使用 XmlTextReader 来做到这一点,但我想
我正在尝试将 11384 个 XML 文件解析到一个 SQLite 数据库中。其中之一: ]> 1 2 我正在使用 SAX 解析器: pub
我需要用 Perl 解析 XML 文件。文件的一部分单独存储,并作为系统实体插入。不过,这个问题很常见。但是我无法获得任何信息来解决它。 ]> &externalContent; 当使
我正在尝试从 xsd 解析 HL7 消息定义。我将模式定义分成两个文件。第一个文件包含实际的消息定义,第二个文件包含消息中的段定义。 我正在尝试调整示例代码以从此处解析 XML https://gis
我正在使用 SAX 解析 MathML 表达式(尽管它是 MathML 的事实可能并不完全相关)。输入字符串示例为 λ 为了让 SAX 解
我正在尝试使用 Java 和 SAX 为 Android 设备解析 XML 文件。我从互联网上获取,在解析它时,我得到一个 ExpatException :字符“é”的格式不正确(无效标记)。有没有办
我正在尝试使用java中的sax读取xml文件。我只获得 endElement 的输出,但无法找出 startElement 出了什么问题。 这是我的处理程序: public class XMLHan
我正在使用 SAX 解析器来解析具有父级及其子级标记的 XML,如下所示:
我正在尝试从 RSS 提要中提取数据。 RSS 链接 - http://www.thehindu.com/sport/?service=rss ? 这是我的默认处理程序的字符方法。 public vo
我尝试执行下面的代码,但我的 SAX 解析器没有调用 startElement 方法。 下面是我的代码: package getTableStructure; import java.util.Lis
我正在满足一项要求,即我需要拆分大型 XML 并进一步处理。 这是 XML 示例,它可以变成单行。 yongjin 这是我的代码: import java.util.Arrays; import ja
我正在尝试将标签的内容放入我的 java Sax 解析器中的变量中。但是,Characters 方法仅返回 Char 数组。有没有办法将 Char 数组转换为 Int??? public void c
我有下面的代码.. System.setProperty("http.proxyHost","176.6.129.25") ; System.setProp
如何使用 SAX 显示树中最大深度的节点名称。该算法很适合我理解这个概念.. 例如,我应该如何使用 startelement、endelement、startdocument、enddocument
有没有可行的方法使用默认的处理程序类来查找对应的XML标签?例如... 1 1 我想使用 startElement() 和 endElement() 方
我想使用 SAX 解析器从 xml 文件中解析一些数据。我的xml如下: Pies & past Fruits 为了解析这些数据,我扩展了 DefaultHandler。 解析后的输出
我正在构建一个创建 XML 的流程(从各种来源并出于我事先不知道的各种目的),并且我希望将生成的 XML 直接注入(inject)到标准 XML 处理中,例如 SAX、StAX和 DOM。我已经完成了
我有一个由 MS Excel 创建的 XML 文件,其中包含如下元素: 22. Department"GS "NAES "ABCDEF"
我在使用 java sax 解析器打开 stackoverflow 帖子 XML 转储时遇到问题。它识别每个元素的结尾,但似乎跳过了 startElement 方法。我使用示例代码: try {
我是一名优秀的程序员,十分优秀!