我需要从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>
答案 0 :(得分:1)
您的代码有一些问题。首先,您在获得后代之后选择.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
});