ParseOptions

ParseOptions类主要用来解析命令行参数,例如
String options[] = { "-v", "-c", "-p", "-r", "-t", "-m" , "-d" };
String values[] = { null, null, null, null, null, null, "None"};
则,values数组中将存储解析后的各个参数的值。
运行实例:
c:/>java snmpget -v v1  -c public  -p 8001 -m rfc1213.txt 202.117.48.33 .1.3.6.1.2.1.1.1.0
中,ParseOptions解析后:
   values[0]存储有命令行参数中的版本号
   values[1]存储有命令行参数中的团体字符串

// Decompiled by Jad v1.5.8f. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name:   ParseOptions.java

import java.io.PrintStream;
import java.util.Vector;

public class ParseOptions
{

    public ParseOptions(String as[], String as1[], String as2[], String s)
    {
        none = "None";
        Vector vector = new Vector();
        usage_string = s;
        for(i = 0; i < as.length; i++)
        {
            for(j = 0; j < as1.length; j++)
            {
                if(!checkOption(as, as1[j], as2[j]))
                    continue;
                as2[j] = option;
                break;
            }

            if(j >= as1.length)
                if(as[i].charAt(0) == '-')
                    usage_error();
                else
                    vector.addElement(as[i]);
        }

        remArgs = new String[vector.size()];
        for(i = 0; i < vector.size(); i++)
            remArgs[i] = (String)vector.elementAt(i);

    }

    private boolean checkOption(String as[], String s, String s1)
    {
        if(as[i].equals(s))
        {
            if(!none.equals(s1))
            {
                if(++i < as.length)
                    option = as[i];
                else
                    usage_error();
            } else
            {
                option = "Set";
            }
            return true;
        } else
        {
            return false;
        }
    }

    public void usage_error()
    {
        System.out.println("Usage: " + usage_string);
        System.exit(1);
    }

    public String remArgs[];
    public String usage_string;
    String none;
    String option;
    int i;
    int j;
}
 
import { BusinessError } from '@kit.BasicServicesKit'; import { http } from '@kit.NetworkKit'; import { xml, util } from '@kit.ArkTS'; // 定义文章数据接口 interface Article { id: string; title: string; source: string; time: string; category: string; isCollected: boolean; image?: string; content?: string; } @Entry @Component struct ITHomeApp { @State currentTab: 'home' | 'favorite' = 'home'; @State showDetail: boolean = false; @State currentArticle: Article | null = null; @State articles: Article[] = []; @State isLoading: boolean = true; private currentItem: Article | null = null; private inItem: boolean = false; // 解析日期格式 private formatDate(dateString: string): string { try { const date = new Date(dateString); return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`; } catch (e) { return dateString; } } // 从描述中提取图片 private extractImage(description: string): string | undefined { const imgRegex = /<img[^>]+src="([^">]+)"/; const match = description.match(imgRegex); return match ? match[1] : undefined; } // 从描述中提取纯文本内容 private extractContent(description: string): string { return description.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim(); } aboutToAppear() { this.fetchRSSData(); } // 获取RSS数据 fetchRSSData() { this.isLoading = true; const httpRequest = http.createHttp(); httpRequest.request( "https://www.ithome.com/rss/", { method: http.RequestMethod.GET }, (err: BusinessError, data: http.HttpResponse) => { if (err) { console.error(`Request failed, code: ${err.code}, message: ${err.message}`); this.isLoading = false; return; } if (data.responseCode !== http.ResponseCode.OK) { console.error(`Response error, code: ${data.responseCode}`); this.isLoading = false; return; } const textEncoder = new util.TextEncoder(); const buffer = textEncoder.encode(data.result as string); this.parseRSSData(buffer.buffer); } ); } // 标签值回调处理 private handleTagValue(name: string, value: string) { switch (name) { case 'item': if (this.inItem && this.currentItem) { this.articles.push(this.currentItem); } this.currentItem = { id: '', title: '', source: 'IT之家', time: '', category: '', isCollected: false, content: '' }; this.inItem = true; break; case 'title': if (this.inItem && this.currentItem) { this.currentItem.title = value; } break; case 'link': if (this.inItem && this.currentItem) { this.currentItem.id = value; } break; case 'pubDate': if (this.inItem && this.currentItem) { this.currentItem.time = this.formatDate(value); } break; case 'category': if (this.inItem && this.currentItem) { this.currentItem.category = value; } break; case 'description': if (this.inItem && this.currentItem) { this.currentItem.image = this.extractImage(value); this.currentItem.content = this.extractContent(value); } break; case 'source': if (this.inItem && this.currentItem && value) { this.currentItem.source = value.replace('来源:', ''); } break; } } // 解析RSS数据 parseRSSData(buffer: ArrayBuffer) { try { this.articles = []; this.currentItem = null; this.inItem = false; const parser = new xml.XmlPullParser(buffer, 'UTF-8'); // 修复1: 使用显式类型定义回调函数 const callback: (name: string, value: string) => boolean = (name: string, value: string) => { this.handleTagValue(name, value); return true; // 必须返回布尔值 }; // 修复2: 创建符合ParseOptions接口的对象 const options: xml.ParseOptions = { supportDoctype: true, ignoreNamespace: true, tagValueCallbackFunction: callback }; parser.parse(options); if (this.inItem && this.currentItem) { this.articles.push(this.currentItem); } this.isLoading = false; } catch (e) { console.error('RSS解析错误: ' + JSON.stringify(e)); this.isLoading = false; } } // 切换标签页 private changeTab(tab: 'home' | 'favorite') { this.currentTab = tab; } // 显示文章详情 private showArticleDetail(article: Article) { this.currentArticle = article; this.showDetail = true; } // 关闭详情页 private closeDetail() { this.showDetail = false; } // 切换收藏状态 private toggleCollect(article: Article) { const index = this.articles.findIndex(a => a.id === article.id); if (index !== -1) { this.articles[index].isCollected = !this.articles[index].isCollected; this.articles = [...this.articles]; } } build() { Stack() { Column() { this.buildHeader() this.buildTabBar() this.buildContent() } .width('100%') .height('100%') .backgroundColor('#F5F5F5') .visibility(this.showDetail ? Visibility.None : Visibility.Visible) if (this.showDetail && this.currentArticle) { this.buildArticleDetail(this.currentArticle) } if (this.isLoading) { Column() { Progress() .width(60) .height(60) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) .backgroundColor('rgba(0,0,0,0.2)') } } } @Builder buildHeader() { Row() { Text('IT之家') .fontSize(24) .fontWeight(FontWeight.Bold) .fontColor('#FF6700') Blank() Image($r('app.media.ic_public_search')) .width(24) .height(24) .margin({ right: 16 }) .onClick(() => { this.fetchRSSData(); }) Image($r('app.media.ic_public_user')) .width(24) .height(24) } .padding({ left: 16, right: 16, top: 12, bottom: 12 }) .width('100%') .backgroundColor('#FFFFFF') .justifyContent(FlexAlign.SpaceBetween) } @Builder buildTabBar() { Row() { Column() { Text('首页') .fontSize(18) .fontColor(this.currentTab === 'home' ? '#FF6700' : '#666666') .fontWeight(this.currentTab === 'home' ? FontWeight.Bold : FontWeight.Normal) if (this.currentTab === 'home') { Divider() .width(24) .height(3) .color('#FF6700') } } .height(56) .justifyContent(FlexAlign.Center) .onClick(() => this.changeTab('home')) .layoutWeight(1) Column() { Text('收藏') .fontSize(18) .fontColor(this.currentTab === 'favorite' ? '#FF6700' : '#666666') .fontWeight(this.currentTab === 'favorite' ? FontWeight.Bold : FontWeight.Normal) if (this.currentTab === 'favorite') { Divider() .width(24) .height(3) .color('#FF6700') } } .height(56) .justifyContent(FlexAlign.Center) .onClick(() => this.changeTab('favorite')) .layoutWeight(1) } .width('100%') .borderWidth({ bottom: 1 }) .borderColor({ bottom: '#EEEEEE' }) .backgroundColor('#FFFFFF') } @Builder buildContent() { Column() { if (this.articles.length === 0 && !this.isLoading) { Column() { Image($r('app.media.ic_public_refresh')) .width(60) .height(60) .margin({ bottom: 20 }) Text('暂无数据,点击刷新') .fontSize(16) .fontColor('#666666') } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) .onClick(() => this.fetchRSSData()) } else if (this.currentTab === 'home') { List({ space: 8 }) { ForEach(this.articles, (article: Article) => { ListItem() { this.buildArticleItem(article) } .onClick(() => { this.showArticleDetail(article); }) }, (article: Article) => article.id) } .width('100%') .height('100%') .layoutWeight(1) } else { List({ space: 8 }) { ForEach(this.articles.filter(article => article.isCollected), (article: Article) => { ListItem() { this.buildArticleItem(article) } .onClick(() => { this.showArticleDetail(article); }) }, (article: Article) => article.id) } .width('100%') .height('100%') .layoutWeight(1) } } .layoutWeight(1) } @Builder buildArticleItem(article: Article) { Column() { Row() { if (article.image) { Image(article.image) .width(120) .height(80) .objectFit(ImageFit.Cover) .borderRadius(4) .margin({ right: 12 }) } else { Image($r('app.media.ic_public_picture')) .width(120) .height(80) .objectFit(ImageFit.Cover) .borderRadius(4) .margin({ right: 12 }) .backgroundColor('#EAEAEA') } Column() { Text(article.title) .fontSize(16) .fontColor('#333333') .fontWeight(FontWeight.Medium) .maxLines(2) .textOverflow({ overflow: TextOverflow.Ellipsis }) .margin({ bottom: 8 }) Row() { Text(article.source) .fontSize(12) .fontColor('#999999') Text(article.time) .fontSize(12) .fontColor('#999999') .margin({ left: 12 }) Blank() // 修复3: 添加事件参数并返回true阻止冒泡 Image(article.isCollected ? $r('app.media.ic_public_favorite') : $r('app.media.ic_public_favorite_filled')) .width(20) .height(20) .onClick(() => { this.toggleCollect(article); return true; // 阻止事件冒泡 }) } .width('100%') .alignItems(VerticalAlign.Center) } .layoutWeight(1) } .padding(12) .width('100%') .backgroundColor('#FFFFFF') .borderRadius(8) Divider() .color('#EEEEEE') .margin({ left: 12, right: 12 }) } } @Builder buildArticleDetail(article: Article) { Column() { Row() { Image($r('app.media.ic_public_back')) .width(24) .height(24) .onClick(() => this.closeDetail()) Text('文章详情') .fontSize(18) .fontWeight(FontWeight.Bold) .margin({ left: 12 }) Blank() Image(article.isCollected ? $r('app.media.ic_public_favorite_filled') : $r('app.media.ic_public_favorite')) .width(24) .height(24) .onClick(() => this.toggleCollect(article)) } .padding({ left: 16, right: 16, top: 12, bottom: 12 }) .width('100%') .backgroundColor('#FFFFFF') Scroll() { Column() { Text(article.title) .fontSize(22) .fontWeight(FontWeight.Bold) .margin({ top: 16, bottom: 12, left: 16, right: 16 }) Row() { Text(article.source) .fontSize(14) .fontColor('#666666') Text(article.time) .fontSize(14) .fontColor('#666666') .margin({ left: 12 }) } .margin({ bottom: 16, left: 16, right: 16 }) if (article.image) { Image(article.image) .width('100%') .height(200) .objectFit(ImageFit.Cover) .margin({ bottom: 16 }) } Text(article.content || '') .fontSize(16) .lineHeight(24) .margin({ left: 16, right: 16, bottom: 24 }) Text('相关推荐') .fontSize(18) .fontWeight(FontWeight.Bold) .margin({ left: 16, bottom: 12, top: 16 }) ForEach( this.articles.filter(a => a.id !== article.id && a.category === article.category).slice(0, 3), (item: Article) => { Column() { Row() { if (item.image) { Image(item.image) .width(80) .height(60) .objectFit(ImageFit.Cover) .borderRadius(4) .margin({ right: 12 }) } else { Image($r('app.media.ic_public_picture')) .width(80) .height(60) .objectFit(ImageFit.Cover) .borderRadius(4) .margin({ right: 12 }) .backgroundColor('#EAEAEA') } Column() { Text(item.title) .fontSize(14) .fontWeight(FontWeight.Medium) .maxLines(2) .textOverflow({ overflow: TextOverflow.Ellipsis }) .margin({ bottom: 4 }) Row() { Text(item.source) .fontSize(12) .fontColor('#999999') Text(item.time) .fontSize(12) .fontColor('#999999') .margin({ left: 8 }) } } .layoutWeight(1) } .padding(12) .width('100%') Divider() .color('#EEEEEE') .margin({ left: 12, right: 12 }) } .onClick(() => this.showArticleDetail(item)) }, (item: Article) => item.id ) } } .layoutWeight(1) .backgroundColor('#FFFFFF') } .width('100%') .height('100%') .backgroundColor('#FFFFFF') } }为什么会出现Structural typing is not supported (arkts-no-structural-typing) <ArkTSCheck>,<html>Type '{ supportDoctype: true; ignoreNamespace: boolean; tagValueCallbackFunction: (name: string, value: string) => boolean; }' is not assignable to type 'ParseOptions'.<br/>Object literal may only specify known properties, but 'ignoreNamespace' does not exist in type 'ParseOptions'. Did you mean to write 'ignoreNameSpace'? <ArkTSCheck>,Expected 1 arguments, but got 0. <ArkTSCheck>三个问题
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值