Given the following 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>
Is there a better/more correct way to return children of Message WHERE the childrens names start with "ArrayOf" then this?
IEnumerable<XElement> array = from arrayOfX
in document.Root.Elements()
where arrayOfX.Name.ToString().IndexOf("ArrayOf") > -1
select arrayOfX;
PS: This also has an issue for the edge case where IndexOf() will return 0 for a String.Empty value. (Although not sure if thats actually possible in well formatted XML - dont think it is?)
A better way to return objects that model the xml structure? Yes. Create a class that models the xml structure, and serialize the xml as such:
[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;
}
}
Then you can access the array of stocks by:
var message = Message.Load( "<xml>" );
foreach( var stock in message.Stocks )
{
Console.WriteLine( stock );
}
Then, in your 'edge case', you won't have to worry about it. The Stocks array will simply be empt.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.