简体   繁体   English

LINQ to XML LIKE子句

[英]LINQ to XML LIKE clause

Given the following XML 鉴于以下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? 有没有更好/更正确的方法可以返回Message的子级,而子级名称以“ ArrayOf”开头,然后返回?

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. PS:这对于边缘情况也有问题,其中IndexOf()将为String.Empty值返回0。 (Although not sure if thats actually possible in well formatted XML - dont think it is?) (尽管不确定在格式正确的XML中是否真的可行-不要以为是吗?)

A better way to return objects that model the xml structure? 返回建模xml结构的对象的更好方法? Yes. 是。 Create a class that models the xml structure, and serialize the xml as such: 创建一个对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;
        }
    }

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. 股票数组将被清空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM