久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

為什么在運行 StAX Parser 時出現 NullPointerException

Why I get NullPointerException when running StAX Parser?(為什么在運行 StAX Parser 時出現 NullPointerException?)
本文介紹了為什么在運行 StAX Parser 時出現 NullPointerException?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在嘗試用 Java 編寫 StAX XML 解析器,但總是出現 NullPointerException 錯誤.請幫我解決這個問題.完整問題:

<塊引用>

線程main"中的異常;java.lang.NullPointerException 在org.example.shoesshop.parser.STAXParser.parseXMLfile(STAXParser.java:68)在 org.example.shoesshop.parser.STAXParser.main(STAXParser.java:101)

這是 StAX Parser 的一個類:

公共類 STAXParser 擴展 DefaultHandler {私有靜態列表<鞋子>parseXMLfile(字符串文件名){列出<鞋子>shoesList = new ArrayList<>();鞋鞋 = null;XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();嘗試 {XMLEventReader reader = xmlInputFactory.createXMLEventReader(new FileInputStream(fileName));while (reader.hasNext()){XMLEvent xmlEvent = reader.nextEvent();如果(xmlEvent.isStartElement()){StartElement startElement = xmlEvent.asStartElement();if(startElement.getName().getLocalPart().equals(鞋")){鞋=新鞋();屬性 idAttr = startElement.getAttributeByName(new QName("id"));如果(idAttr!= null){shoes.setId(Integer.parseInt(idAttr.getValue()));}} else if (startElement.getName().getLocalPart().equals("title")){xmlEvent = reader.nextEvent();shoes.setTitle(xmlEvent.asCharacters().getData());//錯誤第 68 行} else if (startElement.getName().getLocalPart().equals("brand")){xmlEvent = reader.nextEvent();shoes.setBrand(Brand.fromValue(xmlEvent.asCharacters().getData()));} else if (startElement.getName().getLocalPart().equals("category")){xmlEvent = reader.nextEvent();shoes.setCategory(Category.fromValue(xmlEvent.asCharacters().getData()));} else if (startElement.getName().getLocalPart().equals(season")){xmlEvent = reader.nextEvent();shoes.setSeason(Season.fromValue(xmlEvent.asCharacters().getData()));} else if (startElement.getName().getLocalPart().equals("price")){xmlEvent = reader.nextEvent();shoes.setPrice(Double.parseDouble(xmlEvent.asCharacters().getData()));}}如果(xmlEvent.isEndElement()){EndElement endElement = xmlEvent.asEndElement();if(endElement.getName().getLocalPart().equals(鞋")){shoesList.add(鞋子);}}}} 捕捉(FileNotFoundException | XMLStreamException exc){exc.printStackTrace();} 返回鞋子列表;}公共靜態 void main(String[] args) 拋出異常 {System.out.println(STAX 解析器");System.out.println();System.out.println("結果:
");System.out.println();字符串文件名 = ShoesShop.xml";列出<鞋子>shoesList = parseXMLfile(fileName);//錯誤第101行對于(鞋鞋:shoesList){System.out.println(shoes.toString());}}}

這是一個 XML 文件

還有一個用于鞋子的 Java 類

@XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "鞋子", propOrder = {標題",品牌",類別",季節",性別",詳情",價格"})公共課鞋擴展實體{@XmlElement(必需 = 真)受保護的字符串標題;@XmlElement(必需 = 真)@XmlSchemaType(name = "字符串")受保護的品牌品牌;@XmlElement(必需 = 真)@XmlSchemaType(name = "字符串")受保護的類別類別;@XmlElement(必需 = 真)@XmlSchemaType(name = "字符串")受保護的季節;@XmlElement(必需 = 真)受保護的鞋子.性別性別;@XmlElement(必需 = 真)受保護的鞋子.詳細信息;受保護的雙倍價格;@XmlAttribute(name = "stock", required = true)受保護的布爾庫存;@XmlAttribute(name = "最想要的")受保護的布爾最想要的;公共字符串 getTitle() {返回標題;}公共無效 setTitle(字符串值){this.title = 值;}公共品牌 getBrand(){回歸品牌;}public void setBrand(品牌價值){this.brand = 價值;}公共類別 getCategory(){返回類別;}公共無效 setCategory(類別值){this.category = 值;}公共季節 getSeason(){回歸季節;}公共無效setSeason(季節值){this.season = 價值;}public Shoes.Gender getGender() {返回性別;}公共無效 setGender(Shoes.Gender 值){this.gender = 價值;}公共鞋.詳細信息 getDetails() {退貨詳情;}public void setDetails(Shoes.Details 值) {this.details = 價值;}公共雙getPrice(){退貨價格;}公共無效 setPrice(雙值){this.price = 價值;}公共布爾 isStock() {退貨;}公共無效 setStock(布爾值){this.stock = 價值;}公共布爾 isMostWanted() {返回最想要的;}公共無效 setMostWanted(布爾值){this.most Wanted = 價值;}@XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "", propOrder = {})公共靜態類詳細信息{@XmlElement(必需 = 真)受保護的字符串亮點;@XmlElement(必需 = 真)受保護的字符串組合;公共字符串 getHighlights() {返回亮點;}公共無效setHighlights(字符串值){this.highlights = 價值;}公共字符串 getComposition() {返回組成;}公共無效setComposition(字符串值){this.composition = 價值;}}@XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "", propOrder = {u043cu0443u0436u0441u043au043eu0439或u0416u0435u043du0441u043au0438u0439"})公共靜態類性別{@XmlElementRefs({@XmlElementRef(name = "u0436u0435u043du0441u043au0438u0439", 命名空間 = "http://www.example.org/ShoesShop", type = JAXBElement.class, required = false),@XmlElementRef(name = "u043cu0443u0436u0441u043au043eu0439", 命名空間 = "http://www.example.org/ShoesShop", type = JAXBElement.class, required = false)})受保護的列表<JAXBElement<字符串>>男性或女性;公共列表<JAXBElement<字符串>>getMaleOrFemale() {if (maleOrFemale == null) {maleOrFemale = new ArrayList<JAXBElement<String>>();}返回 this.maleOrFemale;}}@覆蓋公共字符串 toString(){StringBuilder builder = new StringBuilder();builder.append("[title=");builder.append(title);builder.append(", 品牌=");builder.append(品牌);builder.append(", category=");builder.append(類別);builder.append(", season=");builder.append(季節);builder.append(", price=");builder.append(價格);builder.append("]");返回 builder.toString();}}

我還需要知道如何將接收到的數據寫入新的 XML 文件.

解決方案

已更新: 對原始答案的評論:

<塊引用>

它不起作用,它給出了同樣的錯誤

這意味著問題是因為 shoes 變量是 null,這在 debugger 中很容易看到.使用調試器會為我們節省很多時間,所以請開始使用調試器.

為了使 shoesnull,看來代碼遇到了一個不是鞋子元素.

要修復代碼,添加一個空檢查,并在處理 Shoes 元素結束時設置 shoes = null:

} else if (startElement.getName().getLocalPart().equals("title")) {if (shoes != null) {//<===== 添加這個shoes.setTitle(reader.getElementText());//<===== 解決這個問題(見原始答案)}

if (xmlEvent.isEndElement()) {EndElement endElement = xmlEvent.asEndElement();if (endElement.getName().getLocalPart().equals(鞋")) {shoesList.add(鞋子);鞋=空;//<===== 添加這個}}


原始答案

你的代碼是:

} else if (startElement.getName().getLocalPart().equals("title")){xmlEvent = reader.nextEvent();shoes.setTitle(xmlEvent.asCharacters().getData());

問題是代碼沒有檢查如果事件跟在 START_ELEMENT 事件之后的類型.可能是這樣的:

  • 元素很可能是空的,即<title/><title><title/>,在這種情況下下一個事件是 END_ELEMENTasCharacters() 返回 null.

  • 元素有注釋,例如<title><!-- 沒有標題--><title/>,在這種情況下,下一個事件是 COMMENT.p>

  • 元素具有混合內容,例如<title>foo<![CDATA[bar]]><title/>,在這種情況下,下一個事件不是全文.

檢索元素的文本內容是如此常見,以至于他們為此添加了一個輔助方法:getElementText():

<塊引用>

讀取純文本元素的內容.前提條件:當前事件是START_ELEMENT.后置條件:當前事件是對應的END_ELEMENT.

拋出:
XMLStreamException - 如果當前事件不是 START_ELEMENT 或者遇到非文本元素

這意味著你的代碼應該是:

} else if (startElement.getName().getLocalPart().equals("title")) {shoes.setTitle(reader.getElementText());

I'm trying to write a StAX XML Parser in Java, but always get NullPointerException error. Please help me to solve this issue. Full problem:

Exception in thread "main" java.lang.NullPointerException at org.example.shoesshop.parser.STAXParser.parseXMLfile(STAXParser.java:68) at org.example.shoesshop.parser.STAXParser.main(STAXParser.java:101)

Here's a class for StAX Parser:

public class STAXParser extends DefaultHandler {
    private static List<Shoes> parseXMLfile(String fileName){
        List<Shoes> shoesList = new ArrayList<>();
        Shoes shoes = null;
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        try {
            XMLEventReader reader = xmlInputFactory.createXMLEventReader(new FileInputStream(fileName));
            while (reader.hasNext()){
                XMLEvent xmlEvent = reader.nextEvent();
                if(xmlEvent.isStartElement()){
                    StartElement startElement = xmlEvent.asStartElement();
                    if(startElement.getName().getLocalPart().equals("Shoes")){
                        shoes = new Shoes();
                        Attribute idAttr = startElement.getAttributeByName(new QName("id"));
                        if(idAttr != null){
                            shoes.setId(Integer.parseInt(idAttr.getValue()));
                        }
                    } else if (startElement.getName().getLocalPart().equals("title")){
                        xmlEvent = reader.nextEvent();
                        shoes.setTitle(xmlEvent.asCharacters().getData()); // error line 68
                    } else if (startElement.getName().getLocalPart().equals("brand")){
                        xmlEvent = reader.nextEvent();
                        shoes.setBrand(Brand.fromValue(xmlEvent.asCharacters().getData()));
                    } else if (startElement.getName().getLocalPart().equals("category")){
                        xmlEvent = reader.nextEvent();
                        shoes.setCategory(Category.fromValue(xmlEvent.asCharacters().getData()));
                    } else if (startElement.getName().getLocalPart().equals("season")){
                        xmlEvent = reader.nextEvent();
                        shoes.setSeason(Season.fromValue(xmlEvent.asCharacters().getData()));
                    } else if (startElement.getName().getLocalPart().equals("price")){
                        xmlEvent = reader.nextEvent();
                        shoes.setPrice(Double.parseDouble(xmlEvent.asCharacters().getData()));
                    }
                }
                if(xmlEvent.isEndElement()){
                    EndElement endElement = xmlEvent.asEndElement();
                    if(endElement.getName().getLocalPart().equals("Shoes")){
                        shoesList.add(shoes);
                    }
                }
            }
        } catch (FileNotFoundException | XMLStreamException exc) {
            exc.printStackTrace();
        } return shoesList;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("STAX Parser");
        System.out.println();
        System.out.println("Result: 
");
        System.out.println();
        String fileName = "ShoesShop.xml";
        List<Shoes> shoesList = parseXMLfile(fileName); //error line 101
        for (Shoes shoes:shoesList){
            System.out.println(shoes.toString());
        }
    }

}

Here's an XML-file

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type = "text/xsl" href = "ShoesShop.xsl"?>

<ss:ShoesShop xmlns:ss="http://www.example.org/ShoesShop" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.example.org/ShoesShop ShoesShop.xsd ">
  <ss:shoes id="1" stock="true">
    <ss:title>Baltrum</ss:title>
    <ss:brand>Gucci</ss:brand>
    <ss:category>Boots</ss:category>
    <ss:season>fall</ss:season>
    <ss:gender>
      <ss:male>male</ss:male>
    </ss:gender>
    <ss:details>
      <ss:highlights>Highlights text 1</ss:highlights>
      <ss:composition>Composition text 1</ss:composition>
    </ss:details>
    <ss:price>734.0</ss:price>
  </ss:shoes>
  
  
  <ss:shoes id="2" stock="true" mostWanted = "true">
    <ss:title>Amalfi</ss:title>
    <ss:brand>Dior</ss:brand>
    <ss:category>Mules</ss:category>
    <ss:season>winter</ss:season>
    <ss:gender>
      <ss:female>female</ss:female>
    </ss:gender>
    <ss:details>
      <ss:highlights>Highlights text 2</ss:highlights>
      <ss:composition>Composition text 2</ss:composition>
    </ss:details>
    <ss:price>364.0</ss:price>
  </ss:shoes>
  
  <ss:shoes id="3" stock="true" mostWanted = "true">
    <ss:title>Korfu</ss:title>
    <ss:brand>Mary Katrantzou</ss:brand>
    <ss:category>Sneakers</ss:category>
    <ss:season>spring</ss:season>
    <ss:gender>
      <ss:female>female</ss:female>
    </ss:gender>
    <ss:details>
      <ss:highlights>Highlights text 3</ss:highlights>
      <ss:composition>Composition text 3</ss:composition>
    </ss:details>
    <ss:price>173.0</ss:price>
  </ss:shoes>
</ss:ShoesShop>

Also here's a Java class for Shoes

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Shoes", propOrder = {
    "title",
    "brand",
    "category",
    "season",
    "gender",
    "details",
    "price"
})
public class Shoes
    extends Entity
{
    @XmlElement(required = true)
    protected String title;
    @XmlElement(required = true)
    @XmlSchemaType(name = "string")
    protected Brand brand;
    @XmlElement(required = true)
    @XmlSchemaType(name = "string")
    protected Category category;
    @XmlElement(required = true)
    @XmlSchemaType(name = "string")
    protected Season season;
    @XmlElement(required = true)
    protected Shoes.Gender gender;
    @XmlElement(required = true)
    protected Shoes.Details details;
    protected double price;
    @XmlAttribute(name = "stock", required = true)
    protected boolean stock;
    @XmlAttribute(name = "mostWanted")
    protected Boolean mostWanted;

    public String getTitle() {
        return title;
    }

    public void setTitle(String value) {
        this.title = value;
    }
    
    public Brand getBrand(){
        return brand;
    }
    
    public void setBrand(Brand value){
        this.brand = value;
    }
    
    public Category getCategory(){
        return category;
    }
    
    public void setCategory(Category value){
        this.category = value;
    }
    
    public Season getSeason(){
        return season;
    }
    
    public void setSeason(Season value) {
        this.season = value;
    }

    public Shoes.Gender getGender() {
        return gender;
    }

    public void setGender(Shoes.Gender value) {
        this.gender = value;
    }

    public Shoes.Details getDetails() {
        return details;
    }

    public void setDetails(Shoes.Details value) {
        this.details = value;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double value) {
        this.price = value;
    }

    public boolean isStock() {
        return stock;
    }

    public void setStock(boolean value) {
        this.stock = value;
    }

    public Boolean isMostWanted() {
        return mostWanted;
    }

    public void setMostWanted(Boolean value) {
        this.mostWanted = value;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {

    })
    public static class Details {

        @XmlElement(required = true)
        protected String highlights;
        @XmlElement(required = true)
        protected String composition;

        public String getHighlights() {
            return highlights;
        }

        public void setHighlights(String value) {
            this.highlights = value;
        }

        public String getComposition() {
            return composition;
        }

        public void setComposition(String value) {
            this.composition = value;
        }

    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "u043cu0443u0436u0441u043au043eu0439Oru0416u0435u043du0441u043au0438u0439"
    })
    public static class Gender {

        @XmlElementRefs({
            @XmlElementRef(name = "u0436u0435u043du0441u043au0438u0439", namespace = "http://www.example.org/ShoesShop", type = JAXBElement.class, required = false),
            @XmlElementRef(name = "u043cu0443u0436u0441u043au043eu0439", namespace = "http://www.example.org/ShoesShop", type = JAXBElement.class, required = false)
        })
        protected List<JAXBElement<String>> maleOrFemale;

        public List<JAXBElement<String>> getMaleOrFemale() {
            if (maleOrFemale == null) {
                maleOrFemale = new ArrayList<JAXBElement<String>>();
            }
            return this.maleOrFemale;
        }

    }
    
    @Override
    public String toString(){
        StringBuilder builder = new StringBuilder();
        builder.append("[title=");
        builder.append(title);
        builder.append(", brand=");
        builder.append(brand);
        builder.append(", category=");
        builder.append(category);
        builder.append(", season=");
        builder.append(season);
        builder.append(", price=");
        builder.append(price);
        builder.append("]");
        return builder.toString();
    }

}

Also I need to know how to write a received data into a new XML-file.

解決方案

UPDATED: Comment to original answer:

It doesn't work, it gives the same error

That means the problem is because the shoes variable is null, as would have easily been seen with a debugger. Using a debugger would have saved us all a lot of time, so please start using one.

In order for shoes to be null, it appears that the code encountered a <title> element that is not a child of a Shoes element.

To fix the code, add a null-check, and also set shoes = null at the end of processing the Shoes element:

} else if (startElement.getName().getLocalPart().equals("title")) {
    if (shoes != null) { // <===== ADD THIS
        shoes.setTitle(reader.getElementText()); // <===== Fix this (see original answer)
    }

if (xmlEvent.isEndElement()) {
    EndElement endElement = xmlEvent.asEndElement();
    if (endElement.getName().getLocalPart().equals("Shoes")) {
        shoesList.add(shoes);
        shoes = null; // <===== ADD THIS
    }
}


ORIGINAL ANSWER

Your code is:

} else if (startElement.getName().getLocalPart().equals("title")){
    xmlEvent = reader.nextEvent();
    shoes.setTitle(xmlEvent.asCharacters().getData());

The problem is that the code isn't checking what type if event follows the START_ELEMENT event. It could be that:

  • Most likely, the element is empty, i.e. <title/> or <title><title/>, in which case the next event is an END_ELEMENT, and asCharacters() returned null.

  • The element has a comment, e.g. <title><!-- there is no title --><title/>, in which case the next event is a COMMENT.

  • The element has mixed content, e.g. <title>foo<![CDATA[bar]]><title/>, in which case the next event is not the full text.

Retrieving the text content of an element is such a common thing that they added a helper method for that: getElementText():

Reads the content of a text-only element. Precondition: the current event is START_ELEMENT. Postcondition: The current event is the corresponding END_ELEMENT.

Throws:
XMLStreamException - if the current event is not a START_ELEMENT or if a non text element is encountered

Which means that your code should be:

} else if (startElement.getName().getLocalPart().equals("title")) {
    shoes.setTitle(reader.getElementText());

這篇關于為什么在運行 StAX Parser 時出現 NullPointerException?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Upload progress listener not fired (Google drive API)(上傳進度偵聽器未觸發(Google 驅動器 API))
Save file in specific folder with Google Drive SDK(使用 Google Drive SDK 將文件保存在特定文件夾中)
Google Drive Android API - Invalid DriveId and Null ResourceId(Google Drive Android API - 無效的 DriveId 和 Null ResourceId)
Google drive api services account view uploaded files to google drive using java(谷歌驅動api服務賬戶查看上傳文件到谷歌驅動使用java)
Google Drive service account returns 403 usageLimits(Google Drive 服務帳號返回 403 usageLimits)
com.google.api.client.json.jackson.JacksonFactory; missing in Google Drive example(com.google.api.client.json.jackson.JacksonFactory;Google Drive 示例中缺少)
主站蜘蛛池模板: 国产精品精品视频一区二区三区 | 国产在线第一页 | 手机看片1 | 精品久久久久久亚洲综合网站 | 在线看av的网址 | 中文字幕 在线观看 | 日韩精品免费在线观看 | 日韩精品一区二区三区中文字幕 | 亚洲国产精品99久久久久久久久 | 欧美影院| 国产精品毛片一区二区在线看 | 亚洲精品中文字幕在线 | 日本一区二区影视 | 久久国产精品视频免费看 | 国精产品一区二区三区 | 国产精品久久久久久久岛一牛影视 | 亚洲精品欧洲 | 欧美激情va永久在线播放 | 一级黄色夫妻生活 | 久久不卡日韩美女 | 久久精品一级 | 中午字幕在线观看 | 日韩精品一区二区三区 | 中文字幕亚洲欧美日韩在线不卡 | 特级黄色毛片 | www国产亚洲精品久久网站 | 亚洲国产成人精品女人久久久 | 日本精品在线播放 | 国产一级片网站 | 免费在线观看一区二区 | 国产精品成人一区二区三区 | 一区二区三区四区视频 | 久久精品福利 | 伊人免费在线观看高清 | 久久久久黄色 | 中文字幕一区二区三区四区 | 久久精品色欧美aⅴ一区二区 | 色视频在线播放 | 日本成人毛片 | 国产乱码精品一区二区三区中文 | 欧洲一区在线观看 |