[英]Loop each Items in c# using XElement
I am facing some difficulty in swapping the id
attribute in the list of Item
s in a C# XDocument
. 我在交换C#
XDocument
的Item
列表中的id
属性时遇到一些困难。 The id
is a reference. 该
id
是参考。
Input: 输入:
<Items>
<Item base="book_bookref1_ref1">
<Name>Test1</Name>
<Ref>bookref1</Ref>
</Item>
<Item base="book_bookref1_ref2">
<Name>Test2</Name>
<Ref>bookref1</Ref>
</Item>
<Item base="book_bookref2_ref1">
<Name>Test3</Name>
<Ref>bookref2</Ref>
</Item>
<Item base="book_bookref2_ref2">
<Name>Test4</Name>
<Ref>bookref2</Ref>
</Item>
</Items>
Expected Output: 预期产量:
<Items>
<Item base="book_bookref1_ref1" id="book_bookref1_ref2">
<Name>Test1</Name>
<Ref>bookref1</Ref>
</Item>
<Item base="book_bookref1_ref2" id="book_bookref1_ref1">
<Name>Test2</Name>
<Ref>bookref1</Ref>
</Item>
<Item base="book_bookref2_ref1" id="book_bookref2_ref2">
<Name>Test3</Name>
<Ref>bookref2</Ref>
</Item>
<Item base="book_bookref2_ref2" id="bookref2_ref1">
<Name>Test4</Name>
<Ref>bookref2</Ref>
</Item>
</Items>
There is a tag <Ref>
where one part of value ex:bookref1
is a reference for Base attribute book_bookref1_ref1
for the 1st and 2nd Item
. 有一个标记
<Ref>
,其中ex:bookref1
值的一部分是对第一项和第二 Item
基本属性book_bookref1_ref1
的引用。
I need to write the 2nd 'id' to the 1st Item
and write the 1st id
to the 2nd Item
in the loop. 我需要在循环中将第二个“ id”写入第一
Item
,并将第一个id
写入第二Item
。 Similarly for the 3rd and 4th Item
. 同样,对于第3和第4
Item
。 There can be many but it's like a combination (1 & 2, 3 & 4, 5 & 6, etc). 可以有很多,但这就像一个组合(1和2、3和4、5和6等)。
The problem here is there can be multiple Item
s and there is no relation in the Item
to map the Id
attribute. 这里的问题是可以有多个
Item
S和存在的没有关系Item
映射的Id
属性。
The code I'm using is loading XMLDocument
into XDocument
getting the Item
s in LINQ. 我正在使用的代码将
XMLDocument
加载到XDocument
,从而在LINQ中获得Item
。
Var doc = XDocument.Load(xml)
var ItemsList
foreach(var itm in ItemsList)
{
// I'm stuck here. How do we get the id attribute value based on Ref tag?
}
Please let me know your suggestions. 请让我知道您的建议。
Nothing in XML is impossible with a little LINQ (and MoreLinq , in this example): 有了一点LINQ(在这个示例中,还有MoreLinq) ,XML的一切都是不可能的:
var xdoc = XDocument.Parse(input);
foreach(var pair in xdoc.XPathSelectElements("Items/Item").Batch(2).ToArray())
{
pair[0].SetAttributeValue(XName.Get("id"), pair[1].Attribute(XName.Get("base")).Value);
pair[1].SetAttributeValue(XName.Get("id"), pair[0].Attribute(XName.Get("base")).Value);
}
This enumerates not each Item
, not each Item
pair (two elements in a batch). 这不是枚举每个
Item
,也不枚举每个Item
对(一批中的两个元素)。 You only need to tweak this to decide what to do if an odd element remains at the end of the loop. 您只需要进行调整,以决定如果在循环末尾保留了奇数元素,该怎么办。
MoreLinq is for .Batch()
extension method, but if you need, you can easily write it yourself. MoreLinq适用于
.Batch()
扩展方法,但是如果需要,您可以自己编写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.