LINQ to XML 查询(基本)
我有一个以下格式的 xml,
"<root>"
"<page>"
"<title>text</title>"
"<text attrib1="1">some text</text>"
"<text attrib1="2">some text</text>"
"<text attrib1="3">some text</text>"
"<text attrib1="4">some text</text>"
"</page>"
"<page>"
"<title>text</title>"
"<text attrib1="1">some text</text>"
"<text attrib1="2">some text</text>"
"<text attrib1="3">some text</text>"
"<text attrib1="4">some text</text>"
"</page>"
"</root>"
忽略“”,
现在我想要这样的结果 xml,
"<root>"
"<title>text</title>"
"<text attrib1="4">some text</text>"
"<title>text</title>"
"<text attrib1="4">some text</text>"
"</root>"
这可以在一个查询中实现吗? 我通过使用两个查询尝试了以下操作,
var titleElms =
from t in allElements
select
new
{
Title = t.Element("title")
};
var textElms =
from t in allText
where (string)t.Attribute("attrib1").Value == "4"
select
t;
但我对此不满意。那么还有其他方法吗?请帮忙。
I have an xml in the following format
"<root>"
"<page>"
"<title>text</title>"
"<text attrib1="1">some text</text>"
"<text attrib1="2">some text</text>"
"<text attrib1="3">some text</text>"
"<text attrib1="4">some text</text>"
"</page>"
"<page>"
"<title>text</title>"
"<text attrib1="1">some text</text>"
"<text attrib1="2">some text</text>"
"<text attrib1="3">some text</text>"
"<text attrib1="4">some text</text>"
"</page>"
"</root>"
ignore " "
now i want the resultant xml like this
"<root>"
"<title>text</title>"
"<text attrib1="4">some text</text>"
"<title>text</title>"
"<text attrib1="4">some text</text>"
"</root>"
can this be achieved in one query?
I tried the following by using two queries
var titleElms =
from t in allElements
select
new
{
Title = t.Element("title")
};
var textElms =
from t in allText
where (string)t.Attribute("attrib1").Value == "4"
select
t;
I am not happy with it. So is there any other approach? pls help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为这会给你想要的东西,因为查询将产生一个 Ienumerable 对象。意味着您想要一个具有大量标题和文本字段的单个对象。这将返回一个对象,其标题和文本是 Ienumerable 对象中的对象。
因此,在您的示例中,您将有一个带有两个对象的对象,每个匿名对象现在都包含标题和文本。一旦你有了这个,你就可以按照你想要的方式构建 xml。它与您的解决方案并没有太大不同,但根据要求,它会给您一个 linq 查询来使用。或者至少给你一个可以借鉴的想法。
希望这至少能给你带来一些新想法
I'm don't think this will give you exactly what you want as the query will result in an Ienumerable object. Meaning where you want a single object with lots of title and text fields. This will return an object with title and text being objects within an Ienumerable object.
so in your example you will have an object with two object, each of these anonymous objects now holding the title and text. once you have this, you can build up the xml the way you want. It's not really that much different from your solution but as requested, it will give you one linq query to work with. Or at the very least give you an idea to build on.
Hope this, at least, gives you a couple new ideas