[英]Get Specific Element on Different XMLs
我需要從xml string
獲取特定元素,以了解其對應的concrete type
以deserialize
它。 讓我們將Function Code
稱為特定元素,獲取此元素對我來說有點挑戰。
每個function code
對應一個特定的架構設計,如下所示:
1 <?xml version="1.0" encoding="utf-8"?>
2 <Document xmlns="some.namespace.of.schema.design.1">
3 <SchemaDesign1>
4 <Header>
5 <FunctionCode>FunctionCode1</FunctionCode>
6 <OtherElement1>...</OtherElement1>
7 <OtherElement2>...</OtherElement2>
我需要第line 5
上的Function Code元素的值是FunctionCode1
。 但是請注意,在line 3
上,元素名稱也特定於其concrete type
。
因此,對於另一個功能代碼,例如FunctionCode2
,第line 3
上的元素將不同:
1 <?xml version="1.0" encoding="utf-8"?>
2 <Document xmlns="some.namespace.of.schema.design.2">
3 <SchemaDesign2>
4 <Header>
5 <FunctionCode>FunctionCode2</FunctionCode>
6 <OtherElement1>...</OtherElement1>
7 <OtherElement2>...</OtherElement2>
我只能想到使用string.IndexOf("<FunctionCode>")
並獲取function code
的值,直到找到相應的結束標記為止。 是否有一個更好的方法而不讀取整個字符串?
這是我得到的示例XML
:
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:caaa.013.001.07">
<AccptrDgnstcReq>
<Hdr>
<MsgFctn>DGNP</MsgFctn>
<PrtcolVrsn>6.0</PrtcolVrsn>
<XchgId>378</XchgId>
<CreDtTm>2013-08-08T22:18:35.07+02:00</CreDtTm>
<InitgPty>
<Id>66000001</Id>
<Tp>OPOI</Tp>
<Issr>ACQR</Issr>
</InitgPty>
<RcptPty>
<Id>epas-acquirer-1</Id>
<Tp>ACQR</Tp>
</RcptPty>
</Hdr>
<DgnstcReq>
<Envt>
<Acqrr>
<Id>
<Id>9287351</Id>
</Id>
<ParamsVrsn>2013-08-07 08:00:00</ParamsVrsn>
</Acqrr>
<MrchntId>
<Id>EPASMER001</Id>
</MrchntId>
<POIId>
<Id>66000001</Id>
<Tp>OPOI</Tp>
<Issr>ACQR</Issr>
</POIId>
</Envt>
</DgnstcReq>
<SctyTrlr>
<CnttTp>AUTH</CnttTp>
<AuthntcdData>
<Rcpt>
<KEK>
<KEKId>
<KeyId>SpecV1TestKey</KeyId>
<KeyVrsn>2010060715</KeyVrsn>
<DerivtnId>OYclpQE=</DerivtnId>
</KEKId>
<KeyNcrptnAlgo>
<Algo>DKP9</Algo>
</KeyNcrptnAlgo>
<NcrptdKey>4pAgABc=</NcrptdKey>
</KEK>
</Rcpt>
<MACAlgo>
<Algo>MCCS</Algo>
</MACAlgo>
<NcpsltdCntt>
<CnttTp>DATA</CnttTp>
</NcpsltdCntt>
<MAC>3Dahc1K96Pc=</MAC>
</AuthntcdData>
</SctyTrlr>
</AccptrDgnstcReq>
</Document>
因此,考慮你有兩個XDocument
,對每個樣品XML,叫doc1
和doc2
分別,那么這段代碼:
var ns1 = doc1.Root.GetDefaultNamespace();
var ns2 = doc2.Root.GetDefaultNamespace();
var functionCode1 = doc1.Root.Descendants(ns1 + "FunctionCode").First().Value;
var functionCode2 = doc2.Root.Descendants(ns2 + "FunctionCode").First().Value;
Console.WriteLine(functionCode1);
Console.WriteLine(functionCode2);
...生產:
FunctionCode1 FunctionCode2
因此,考慮到您有這種格式的未知XML文檔,通常的情況是:
var ns = doc.Root.GetDefaultNamespace();
var functionCode = doc.Root.Descendants(ns + "FunctionCode").First().Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.