给出以下XML
<?xml version="1.0"?>
<Message>
<ArrayOfStock xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Stock>
<StockID>9cddb639-25ee-4415-be07-3109e5ae9883</StockID>
<Description>Stock Item 0</Description>
</Stock>
<Stock>
<StockID>f89f02f9-b359-48c8-8d2f-3a950837f4fb</StockID>
<Description>Stock Item 1</Description>
</Stock>
<Stock>
<StockID>3338ec80-f59e-4979-a04c-f7d52e386bb7</StockID>
<Description>Stock Item 2</Description>
</Stock>
</ArrayOfStock>
</Message>
有没有更好/更正确的方法来返回消息的子项WHERE子项的名称以“ArrayOf”开头呢?
IEnumerable<XElement> array = from arrayOfX
in document.Root.Elements()
where arrayOfX.Name.ToString().IndexOf("ArrayOf") > -1
select arrayOfX;
PS:对于边缘情况也存在问题,其中IndexOf()将为String.Empty值返回0。 (虽然不确定那些在格式良好的XML中是否真的有可能 - 不要认为它是?)
答案 0 :(得分:3)
答案 1 :(得分:0)
返回模拟xml结构的对象的更好方法是什么?是。创建一个对xml结构进行建模的类,并将xml序列化为:
[XmlRootAttribute("ArrayOfStocks")]
public class Stocks
{
[XmlArrayItem(typeof(Stock))]
public Stock[] Stocks { get; set; }
}
public class Stock
{
public StockID { get; set; }
public Description { get; set; }
}
public class Message
{
public Stocks { get; set; }
public static Message Load( string xml )
{
var deserializer = new XmlSerializer( typeof( Stocks ) );
Stocks stocks = null;
using( TextReader textReader = new StringReader( data ) )
{
stocks = (Stocks)deserializer.Deserialize( textReader );
}
return stocks;
}
}
然后您可以通过以下方式访问股票阵列:
var message = Message.Load( "<xml>" );
foreach( var stock in message.Stocks )
{
Console.WriteLine( stock );
}
然后,在你的'边缘案例'中,你不必担心它。 Stocks数组将只是空出来。