使用 xsdgen 解组 XML
时间:2024-04-07
浏览:259
作者:佚名
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《使用 xsdgen 解组 XML》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
我正在尝试使用 golang 解析 xml 文件。
我使用 xsdgen 生成结构部分
我无法使用 xml.unmarshal(bytevalue, &data) 解析文件
我期望程序打印:grandtotalamount.value 这是 671.15,但它打印的是 0。
变量 data 似乎为空,因为这一行没有按我的预期工作:
xml.unmarshal(bytevalue, &data)
我没有看到任何编译错误(或者我不知道在哪里可以找到它们)
我觉得我错过了一些东西,你能帮我吗?
xsd 文件:https://gist.github.com/hyperi0n/a5eb805d9f91de84d341ea75cfe6d1bf
xml 文件:
<?xml version='1.0' encoding='utf-8'?>
<rsm:crossindustryinvoice xmlns:qdt="urn:un:unece:uncefact:data:standard:qualifieddatatype:100" xmlns:ram="urn:un:unece:uncefact:data:standard:reusableaggregatebusinessinformationentity:100" xmlns:rsm="urn:un:unece:uncefact:data:standard:crossindustryinvoice:100" xmlns:udt="urn:un:unece:uncefact:data:standard:unqualifieddatatype:100" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance">
<rsm:exchangeddocumentcontext>
<ram:guidelinespecifieddocumentcontextparameter>
<ram:id>urn:factur-x.eu:1p0:minimum</ram:id>
</ram:guidelinespecifieddocumentcontextparameter>
</rsm:exchangeddocumentcontext>
<rsm:exchangeddocument>
<ram:id>fa-2017-0010</ram:id>
<ram:typecode>380</ram:typecode>
<ram:issuedatetime>
<udt:datetimestring format="102">20171113</udt:datetimestring>
</ram:issuedatetime>
</rsm:exchangeddocument>
<rsm:supplychaintradetransaction>
<ram:applicableheadertradeagreement>
<ram:sellertradeparty>
<ram:name>au bon moulin</ram:name>
<ram:specifiedlegalorganization>
<ram:id schemeid="0002">99999999800010</ram:id>
</ram:specifiedlegalorganization>
<ram:postaltradeaddress>
<ram:countryid>fr</ram:countryid>
</ram:postaltradeaddress>
<ram:specifiedtaxregistration>
<ram:id schemeid="va">fr11999999998</ram:id>
</ram:specifiedtaxregistration>
</ram:sellertradeparty>
<ram:buyertradeparty>
<ram:name>ma jolie boutique</ram:name>
<ram:specifiedlegalorganization>
<ram:id schemeid="0002">78787878400035</ram:id>
</ram:specifiedlegalorganization>
<ram:postaltradeaddress>
<ram:countryid>fr</ram:countryid>
</ram:postaltradeaddress>
<ram:specifiedtaxregistration>
<ram:id schemeid="va">fr19787878784</ram:id>
</ram:specifiedtaxregistration>
</ram:buyertradeparty>
<ram:buyerorderreferenceddocument>
<ram:issuerassignedid>po445</ram:issuerassignedid>
</ram:buyerorderreferenceddocument>
</ram:applicableheadertradeagreement>
<ram:applicableheadertradedelivery/>
<ram:applicableheadertradesettlement>
<ram:invoicecurrencycode>eur</ram:invoicecurrencycode>
<ram:specifiedtradesettlementheadermonetarysummation>
<ram:taxbasistotalamount>624.90</ram:taxbasistotalamount>
<ram:taxtotalamount currencyid="eur">46.25</ram:taxtotalamount>
<ram:grandtotalamount>671.15</ram:grandtotalamount>
<ram:duepayableamount>470.15</ram:duepayableamount>
</ram:specifiedtradesettlementheadermonetarysummation>
</ram:applicableheadertradesettlement>
</rsm:supplychaintradetransaction>
</rsm:crossindustryinvoice>
转到文件:
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type AmountType struct {
Value float64 `xml:",chardata"`
CurrencyID string `xml:"currencyID,attr,omitempty"`
}
// May be one of 1A, AD, AE, AF, AG, AI, AL, AM, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BL, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BY, BZ, CA, CC, CD, CF, CG, CH, CI, CK, CL, CM, CN, CO, CR, CU, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, ET, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IQ, IR, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KP, KR, KW, KY, KZ, LA, LB, LC, LI, LK, LR, LS, LT, LU, LV, LY, MA, MC, MD, ME, MF, MG, MH, MK, ML, MM, MN, MO, MP, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NI, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PS, PT, PW, PY, QA, RE, RO, RS, RU, RW, SA, SB, SC, SD, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SO, SR, SS, ST, SV, SX, SY, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TR, TT, TV, TW, TZ, UA, UG, UM, US, UY, UZ, VA, VC, VE, VG, VI, VN, VU, WF, WS, YE, YT, ZA, ZM, ZW
type CountryIDContentType string
type CrossIndustryInvoiceType struct {
ExchangedDocumentContext ExchangedDocumentContextType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 ExchangedDocumentContext"`
ExchangedDocument ExchangedDocumentType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 ExchangedDocument"`
SupplyChainTradeTransaction SupplyChainTradeTransactionType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 SupplyChainTradeTransaction"`
}
// May be one of AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BOV, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHE, CHF, CHW, CLF, CLP, CNY, COP, COU, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MXV, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLL, SOS, SRD, SSP, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, USD, USN, UYI, UYU, UYW, UZS, VES, VND, VUV, WST, XAF, XAG, XAU, XBA, XBB, XBC, XBD, XCD, XDR, XOF, XPD, XPF, XPT, XSU, XTS, XUA, XXX, YER, ZAR, ZMW, ZWL
type CurrencyCodeContentType string
type DateTimeString struct {
Value string `xml:",chardata"`
Format string `xml:"format,attr"`
}
type DateTimeType struct {
DateTimeString DateTimeString `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 DateTimeString"`
}
// May be one of 80, 81, 82, 83, 84, 130, 202, 203, 204, 211, 261, 262, 295, 296, 308, 325, 326, 380, 381, 383, 384, 385, 386, 387, 388, 389, 390, 393, 394, 395, 396, 420, 456, 457, 458, 527, 575, 623, 633, 751, 780, 935
type DocumentCodeContentType string
type DocumentContextParameterType struct {
ID IDType `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 ID,omitempty"`
}
type ExchangedDocumentContextType struct {
BusinessProcessSpecifiedDocumentContextParameter DocumentContextParameterType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 BusinessProcessSpecifiedDocumentContextParameter,omitempty"`
GuidelineSpecifiedDocumentContextParameter DocumentContextParameterType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 GuidelineSpecifiedDocumentContextParameter"`
}
type ExchangedDocumentType struct {
ID IDType `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 ID"`
TypeCode DocumentCodeContentType `xml:"urn:un:unece:uncefact:data:standard:QualifiedDataType:100 TypeCode"`
IssueDateTime DateTimeType `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 IssueDateTime"`
}
type HeaderTradeAgreementType struct {
BuyerReference string `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 BuyerReference,omitempty"`
SellerTradeParty TradePartyType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 SellerTradeParty"`
BuyerTradeParty TradePartyType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 BuyerTradeParty"`
BuyerOrderReferencedDocument ReferencedDocumentType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 BuyerOrderReferencedDocument,omitempty"`
}
type HeaderTradeDeliveryType struct {
}
type HeaderTradeSettlementType struct {
InvoiceCurrencyCode CurrencyCodeContentType `xml:"urn:un:unece:uncefact:data:standard:QualifiedDataType:100 InvoiceCurrencyCode"`
SpecifiedTradeSettlementHeaderMonetarySummation TradeSettlementHeaderMonetarySummationType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 SpecifiedTradeSettlementHeaderMonetarySummation"`
}
type IDType struct {
Value string `xml:",chardata"`
SchemeID string `xml:"schemeID,attr,omitempty"`
}
type LegalOrganizationType struct {
ID IDType `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 ID,omitempty"`
}
type ReferencedDocumentType struct {
IssuerAssignedID IDType `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 IssuerAssignedID"`
}
type SupplyChainTradeTransactionType struct {
ApplicableHeaderTradeAgreement HeaderTradeAgreementType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 ApplicableHeaderTradeAgreement"`
ApplicableHeaderTradeDelivery HeaderTradeDeliveryType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 ApplicableHeaderTradeDelivery"`
ApplicableHeaderTradeSettlement HeaderTradeSettlementType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 ApplicableHeaderTradeSettlement"`
}
type TaxRegistrationType struct {
ID IDType `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 ID"`
}
type TradeAddressType struct {
PostcodeCode string `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 PostcodeCode,omitempty"`
LineOne string `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 LineOne,omitempty"`
LineTwo string `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 LineTwo,omitempty"`
LineThree string `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 LineThree,omitempty"`
CityName string `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 CityName,omitempty"`
CountryID CountryIDContentType `xml:"urn:un:unece:uncefact:data:standard:QualifiedDataType:100 CountryID"`
CountrySubDivisionName string `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 CountrySubDivisionName,omitempty"`
}
type TradePartyType struct {
Name string `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 Name"`
SpecifiedLegalOrganization LegalOrganizationType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 SpecifiedLegalOrganization,omitempty"`
PostalTradeAddress TradeAddressType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 PostalTradeAddress,omitempty"`
SpecifiedTaxRegistration []TaxRegistrationType `xml:"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 SpecifiedTaxRegistration,omitempty"`
}
type TradeSettlementHeaderMonetarySummationType struct {
TaxBasisTotalAmount AmountType `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 TaxBasisTotalAmount"`
TaxTotalAmount AmountType `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 TaxTotalAmount,omitempty"`
GrandTotalAmount AmountType `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 GrandTotalAmount"`
DuePayableAmount AmountType `xml:"urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100 DuePayableAmount"`
}
func main() {
xmlFile, err := os.Open("invoice.xml")
if err != nil {
fmt.Println(err)
}
defer xmlFile.Close()
byteValue, _ := ioutil.ReadAll(xmlFile)
fmt.Println(string(byteValue))
var data CrossIndustryInvoiceType
xml.Unmarshal(byteValue, &data)
fmt.Println(data.SupplyChainTradeTransaction.ApplicableHeaderTradeSettlement.SpecifiedTradeSettlementHeaderMonetarySummation.GrandTotalAmount.Value)
}解决方案
我认为这与 Go Issue #13400 有关。命名空间前缀似乎存在问题。事实上,您可以在解组时忽略结构标记中的前缀。
以下代码应该适合您:
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"log"
"os"
)
type amounttype struct {
value float64 `xml:",chardata"`
currencyid string `xml:"currencyid,attr,omitempty"`
}
// may be one of 1a, ad, ae, af, ag, ai, al, am, ao, aq, ar, as, at, au, aw, ax, az, ba, bb, bd, be, bf, bg, bh, bi, bj, bl, bm, bn, bo, bq, br, bs, bt, bv, bw, by, bz, ca, cc, cd, cf, cg, ch, ci, ck, cl, cm, cn, co, cr, cu, cv, cw, cx, cy, cz, de, dj, dk, dm, do, dz, ec, ee, eg, eh, er, es, et, fi, fj, fk, fm, fo, fr, ga, gb, gd, ge, gf, gg, gh, gi, gl, gm, gn, gp, gq, gr, gs, gt, gu, gw, gy, hk, hm, hn, hr, ht, hu, id, ie, il, im, in, io, iq, ir, is, it, je, jm, jo, jp, ke, kg, kh, ki, km, kn, kp, kr, kw, ky, kz, la, lb, lc, li, lk, lr, ls, lt, lu, lv, ly, ma, mc, md, me, mf, mg, mh, mk, ml, mm, mn, mo, mp, mq, mr, ms, mt, mu, mv, mw, mx, my, mz, na, nc, ne, nf, ng, ni, nl, no, np, nr, nu, nz, om, pa, pe, pf, pg, ph, pk, pl, pm, pn, pr, ps, pt, pw, py, qa, re, ro, rs, ru, rw, sa, sb, sc, sd, se, sg, sh, si, sj, sk, sl, sm, sn, so, sr, ss, st, sv, sx, sy, sz, tc, td, tf, tg, th, tj, tk, tl, tm, tn, to, tr, tt, tv, tw, tz, ua, ug, um, us, uy, uz, va, vc, ve, vg, vi, vn, vu, wf, ws, ye, yt, za, zm, zw
type countryidcontenttype string
type crossindustryinvoicetype struct {
exchangeddocumentcontext exchangeddocumentcontexttype `xml:"exchangeddocumentcontext"`
exchangeddocument exchangeddocumenttype `xml:"exchangeddocument"`
supplychaintradetransaction supplychaintradetransactiontype `xml:"supplychaintradetransaction"`
}
// may be one of aed, afn, all, amd, ang, aoa, ars, aud, awg, azn, bam, bbd, bdt, bgn, bhd, bif, bmd, bnd, bob, bov, brl, bsd, btn, bwp, byn, bzd, cad, cdf, che, chf, chw, clf, clp, cny, cop, cou, crc, cuc, cup, cve, czk, djf, dkk, dop, dzd, egp, ern, etb, eur, fjd, fkp, gbp, gel, ghs, gip, gmd, gnf, gtq, gyd, hkd, hnl, hrk, htg, huf, idr, ils, inr, iqd, irr, isk, jmd, jod, jpy, kes, kgs, khr, kmf, kpw, krw, kwd, kyd, kzt, lak, lbp, lkr, lrd, lsl, lyd, mad, mdl, mga, mkd, mmk, mnt, mop, mru, mur, mvr, mwk, mxn, mxv, myr, mzn, nad, ngn, nio, nok, npr, nzd, omr, pab, pen, pgk, php, pkr, pln, pyg, qar, ron, rsd, rub, rwf, sar, sbd, scr, sdg, sek, sgd, shp, sll, sos, srd, ssp, stn, svc, syp, szl, thb, tjs, tmt, tnd, top, try, ttd, twd, tzs, uah, ugx, usd, usn, uyi, uyu, uyw, uzs, ves, vnd, vuv, wst, xaf, xag, xau, xba, xbb, xbc, xbd, xcd, xdr, xof, xpd, xpf, xpt, xsu, xts, xua, xxx, yer, zar, zmw, zwl
type currencycodecontenttype string
type datetimestring struct {
value string `xml:",chardata"`
format string `xml:"format,attr"`
}
type datetimetype struct {
datetimestring datetimestring `xml:"datetimestring"`
}
// may be one of 80, 81, 82, 83, 84, 130, 202, 203, 204, 211, 261, 262, 295, 296, 308, 325, 326, 380, 381, 383, 384, 385, 386, 387, 388, 389, 390, 393, 394, 395, 396, 420, 456, 457, 458, 527, 575, 623, 633, 751, 780, 935
type documentcodecontenttype string
type documentcontextparametertype struct {
id idtype `xml:"id,omitempty"`
}
type exchangeddocumentcontexttype struct {
businessprocessspecifieddocumentcontextparameter documentcontextparametertype `xml:"businessprocessspecifieddocumentcontextparameter,omitempty"`
guidelinespecifieddocumentcontextparameter documentcontextparametertype `xml:"guidelinespecifieddocumentcontextparameter"`
}
type exchangeddocumenttype struct {
id idtype `xml:"id"`
typecode documentcodecontenttype `xml:"typecode"`
issuedatetime datetimetype `xml:"issuedatetime"`
}
type headertradeagreementtype struct {
buyerreference string `xml:"buyerreference,omitempty"`
sellertradeparty tradepartytype `xml:"sellertradeparty"`
buyertradeparty tradepartytype `xml:"buyertradeparty"`
buyerorderreferenceddocument referenceddocumenttype `xml:"buyerorderreferenceddocument,omitempty"`
}
type headertradedeliverytype struct {
}
type headertradesettlementtype struct {
invoicecurrencycode currencycodecontenttype `xml:"invoicecurrencycode"`
specifiedtradesettlementheadermonetarysummation tradesettlementheadermonetarysummationtype `xml:"specifiedtradesettlementheadermonetarysummation"`
}
type idtype struct {
value string `xml:",chardata"`
schemeid string `xml:"schemeid,attr,omitempty"`
}
type legalorganizationtype struct {
id idtype `xml:"id,omitempty"`
}
type referenceddocumenttype struct {
issuerassignedid idtype `xml:"issuerassignedid"`
}
type supplychaintradetransactiontype struct {
applicableheadertradeagreement headertradeagreementtype `xml:"applicableheadertradeagreement"`
applicableheadertradedelivery headertradedeliverytype `xml:"applicableheadertradedelivery"`
applicableheadertradesettlement headertradesettlementtype `xml:"applicableheadertradesettlement"`
}
type taxregistrationtype struct {
id idtype `xml:"id"`
}
type tradeaddresstype struct {
postcodecode string `xml:"postcodecode,omitempty"`
lineone string `xml:"lineone,omitempty"`
linetwo string `xml:"linetwo,omitempty"`
linethree string `xml:"linethree,omitempty"`
cityname string `xml:"cityname,omitempty"`
countryid countryidcontenttype `xml:"countryid"`
countrysubdivisionname string `xml:"countrysubdivisionname,omitempty"`
}
type tradepartytype struct {
name string `xml:"name"`
specifiedlegalorganization legalorganizationtype `xml:"specifiedlegalorganization,omitempty"`
postaltradeaddress tradeaddresstype `xml:"postaltradeaddress,omitempty"`
specifiedtaxregistration []taxregistrationtype `xml:"specifiedtaxregistration,omitempty"`
}
type tradesettlementheadermonetarysummationtype struct {
taxbasistotalamount amounttype `xml:"taxbasistotalamount"`
taxtotalamount amounttype `xml:"taxtotalamount,omitempty"`
grandtotalamount amounttype `xml:"grandtotalamount"`
duepayableamount amounttype `xml:"duepayableamount"`
}
func main() {
xmlfile, err := os.open("invoice.xml")
if err != nil {
log.fatalln(err)
}
byted, err := ioutil.readall(xmlfile)
if err != nil {
log.fatalln(err)
}
xmlfile.close()
var data crossindustryinvoicetype
if err := xml.unmarshal(byted, &data); err != nil {
log.fatalln(err)
}
fmt.printf("%v\n", data.supplychaintradetransaction.applicableheadertradesettlement.specifiedtradesettlementheadermonetarysummation.grandtotalamount.value)
}
输出:
671.15
当我使用xsdgen生成iso20022的相关go代码时,我遇到了同样的问题。应该是xsdgen包里面的一些事情。我已阅读有关 xsdgen 配置的所有选项,但没有选项可以忽略使用 xmltag 添加命名空间。
您可能会专注于 xsdgen 包的实现,或者只是在生成的代码的基础上手动省略额外的命名空间。
本篇关于《使用 xsdgen 解组 XML》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
