从包含多行代码的XML中获取结果
本文关键字:获取 结果 XML 包含多 代码 | 更新日期: 2023-09-27 18:09:58
我想获得每个订单的订单行,并将它们作为表格带到电子邮件正文中,如
值1 |值2 |值3
12345 ABC X1_
XML代码:<?xml version="1.0" encoding="utf-8"?><UniversalInterchange xmlns= "http://www.designworker/namespace" version="1.1">
<Header> </Header>
<Body>
<UniversalShipment xmlns="http://www.designworker/namespace" version="1.1">
<Shipment>
<DataContext>
<DataTargetCollection>
<DataTarget>
<Type>SMTPTYPE</Type>
</DataTarget>
</DataTargetCollection>
</DataContext>
<Order>
<OrderNumber>99348234234</OrderNumber>
<OrderLineCollection>
<OrderLine>
<LineNumber>1</LineNumber>
<OrderedQty>455.000</OrderedQty>
<OrderedQtyUnit>
<Code>MORE</Code>
</OrderedQtyUnit>
<Product>
<Code>999LAM01</Code>
<Description>New Design Work</Description>
</Product>
<QuantityMet>1.000</QuantityMet>
<ShortfallQuantity>0</ShortfallQuantity>
</OrderLine>
<OrderLine>
<LineNumber>2</LineNumber>
<OrderedQty>655.000</OrderedQty>
<OrderedQtyUnit>
<Code>SOME</Code>
</OrderedQtyUnit>
<Product>
<Code>999LAM02</Code>
<Description>OLD Design Work </Description>
</Product>
<QuantityMet>3.000</QuantityMet>
<ShortfallQuantity>45</ShortfallQuantity>
</OrderLine>
</OrderLineCollection>
</Order>
</Shipment>
</UniversalShipment>
</Body>
</UniversalInterchange>
我试着用下面的代码来解决这个问题:
var xDoc = XDocument.Parse(xmlValue);
XNamespace nsp = ns;
try
{
var value = xDoc
.Element(nsp + "UniversalInterchange")
.Element(nsp + "Body")
.Element(nsp + "UniversalShipment")
.Element(nsp + "Order")
.Element(nsp + "OrderLine")
.Element(nsp + "LineNumber")
.Value;
return value;
但是当我在顺序中有多个行时,它将不起作用。我怎样才能用更好的方法解决这个问题?
看起来导航路径缺少几个。element()调用。
var orderLines = xDoc
.Element(nsp + "UniversalInterchange")
.Element(nsp + "Body")
.Element(nsp + "UniversalShipment")
.Element(nsp + "Shipment")
.Element(nsp + "Order")
.Element(nsp + "OrderLineCollection")
.Elements(nsp + "OrderLine");
// 1, 2
var lineNumbers = orderLines.Select(x => x.Element(nsp + "LineNumber").Value);
当没有找到一个元素时,. element()返回null。如果需要多个条目,还应该使用。elements()而不是。element()。