LINQ to XML LIKE 子句
给定以下 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>
是否有更好/更正确的方法来返回 Message 的子级,其中子级名称以“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 中这是否真的可能 - 不认为这是可能的?)
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?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
String.StartsWith()
方法?Use the
String.StartsWith()
method?返回对 xml 结构进行建模的对象的更好方法是什么?是的。创建一个对 xml 结构建模的类,并按如下方式序列化 xml:
然后您可以通过以下方式访问股票数组:
然后,在您的“边缘情况”中,您不必担心它。 Stocks 数组将是空的。
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:
Then you can access the array of stocks by:
Then, in your 'edge case', you won't have to worry about it. The Stocks array will simply be empt.