[英]How to get XML elements with LINQ
我需要從XML字符串中選擇的幫助。
在幾分鍾前的一些幫助下,我設法用此代碼解析XML輸入。
foreach (XElement element in xml.Descendants("{" + ns + "}VehicleValue").Elements())
{
Console.WriteLine(element.ToString());
};
(其中ns是名稱空間。)
現在,我想將其選擇為一堆變量(屬性)
var r = xml
.Descendants("{" + ns + "}VehicleValue").Elements()
.Select(x => new
{
#region all the Nodes/Fields
AdjustedEstimatedCostPrice = x.Element("AdjustedEstimatedCostPrice").Value,
AdjustedEstimatedCostPrice_MileageAndCondition = x.Element("AdjustedEstimatedCostPrice_MileageAndCondition").Value,
});
但它不會選擇或填充我的變量。 我以為如果foreach有效並且我對select應用了相同的指令,它將起作用嗎?
<?xml version="1.0" encoding="UTF-8"?>
-<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
-<s:Body>
-<GetConvergedDataRequestResponse xmlns="http://autoinsight.trann.co.za/types" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
-<ConvergedData i:type="ConvergedResults" xmlns:d4p1="http://schemas.datacontract.org/2004/07/Trann.Auto.Convergence.B2B.BusinessModels">
<AccidentHistory i:nil="true"/>
<AlertInfo i:nil="true"/>
<CloneInfo i:nil="true"/>
-<DiskDriveInfo>
<ResultCode i:nil="true"/>
<ResultCodeDescription i:nil="true"/>
<AirbagDetails>DRIVER, PASSENGER</AirbagDetails>
<Alarm>NO</Alarm>
</DiskDriveInfo>
<EnquiryHistory i:nil="true"/>
<FactoryFittedExtras i:nil="true"/>
<Finance i:nil="true"/>
<MileageHistory i:nil="true"/>
-<VehicleCodeAndDescription>
<ResultCode i:nil="true"/>
<ResultCodeDescription i:nil="true"/>
<VehicleCode>60007400</VehicleCode>
</VehicleCodeAndDescription>
<VehicleConfirmationInfo i:nil="true"/>
-<VehicleValueInfo>
-<VehicleValue>
<ResultCode i:nil="true"/>
<ResultCodeDescription i:nil="true"/>
<AdjustCostPrice>0</AdjustCostPrice>
<AdjEstCostPrice>0</AdjEstCostPrice>
<CostPrice>0</CostPrice>
<TradePrice>0</TradePrice>
<VehicleCode>60007400</VehicleCode>
</VehicleValue>
</VehicleValueInfo>
<VesaInfo i:nil="true"/>
</ConvergedData>
<ResponseStatus xmlns:d4p1="http://schemas.servicestack.net/types" i:nil="true"/>
</GetConvergedDataRequestResponse>
</s:Body>
</s:Envelope>
您的代碼有一些問題。 獲取后代后,首先選擇.Elements
。 另外,您缺少名稱空間。 試試這個代碼:
var doc = XDocument.Parse(xml);
XNamespace ns = "http://autoinsight.trann.co.za/types";
var result = doc
.Descendants(ns + "VehicleValue")
.Select(x => new
{
AdjustCostPrice = x.Element(ns + "AdjustCostPrice").Value,
AdjEstCostPrice = x.Element(ns + "AdjEstCostPrice").Value,
CostPrice = x.Element(ns + "CostPrice").Value,
VehicleCode = x.Element(ns + "VehicleCode").Value,
//etc
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.