Strange XElement.XPathSelectElement behaviour

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
<p style="margin:0in 0in 10pt <span style="font-family:Calibri; font-size:small
<p style="margin:0in 0in 10pt <span style="font-size:small <span style="font-family:Calibri Hi,

<p style="margin:0in 0in 10pt <span style="font-size:small <span style="font-family:Calibri I expect the following code loops through all of the StockLine items, print
<span> StockCode and CustomerPoLine (1â3). However, it always prints âStockCode=SKU1, CustomerPoLine=0001â 3 times.
<p style="margin:0in 0in 10pt <span style="font-size:small <span style="font-family:Calibri Could anyone explain why it doesnât print all the 3 linesâ value?
<p style="margin:0in 0in 10pt <span style="font-size:small <span style="font-family:Calibri Thank you.

<pre lang="x-c# using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;

namespace ConsoleApplication3
{
class Program
{

public static string xml = @"
<Order>
<OrderDetails>
<StockLine>
<CustomerPoLine>0001</CustomerPoLine>
<StockCode>SKU1</StockCode>
</StockLine>
<StockLine>
<CustomerPoLine>0002</CustomerPoLine>
<StockCode>SKU2</StockCode>
</StockLine>
<StockLine>
<CustomerPoLine>0003</CustomerPoLine>
<StockCode>SKU3</StockCode>
</StockLine>
</OrderDetails>
</Order>
";


static void Main(string[] args)
{
XElement root = XElement.Parse(xml);
var stockLines = root.Descendants("StockLine").ToList();
root.XPathSelectElement("//StockLine");
string StockCode;
string CustomerPoLine;
foreach (var stockLine in stockLines)
{
//var x = stockLine.XPathSelectElements("//StockCode");// Always returns 3 elements

StockCode = stockLine.XPathSelectElement("//StockCode").Value;
StockCode = stockLine.XPathSelectElement("//StockCode").Value;
CustomerPoLine = stockLine.XPathSelectElement("//CustomerPoLine").Value;
Console.WriteLine("StockCode={0}, CustomerPoLine={1}", StockCode, CustomerPoLine);
}
Console.ReadKey();
}
}
}
[/code]

View the full article
 
Back
Top