简体   繁体   中英

update one xml based on another xml with repetitive elements with linq to xml

I have a source xml:

<Source>
    <First>
        <Name>Name1</Name>
    </First>
    <First>
        <Name>Name2</Name>
    </First>
</Source>

I have an empty target xml, where I want to copy data from the source xml.

Empty target xml is:

<Target>
    <Second>
        <FirstName></FirstName>
    </Second>
    <Second>
        <FirstName></FirstName>
    </Second>
</Target>

After copy the target xml will look:

<Target>
    <Second>
        <FirstName>Name1</FirstName>
    </Second>
    <Second>
        <FirstName>Name2</FirstName>
    </Second>
</Target>

I'm looking for an easy linq to xml solution. The problem is, that I don't know how to update repetitive elements in target xml based on repetitive elements from source xml.

thanks.

You can do that using the following code:

var source = "<Source><First><Name>Name1</Name></First><First><Name>Name2</Name></First></Source>";
var sourceDocument = XDocument.Load(new StringReader(source));

var target = "<Target><Second><FirstName></FirstName></Second><Second><FirstName></FirstName></Second></Target>";
var targetDocument = XDocument.Load(new StringReader(target));

var sourceNameElements = sourceDocument.Descendants("First").Select(first => first.Element("Name")).ToList();
var targetNamesElements = targetDocument.Descendants("Second").Select(second => second.Element("FirstName")).ToList();

for (var i = 0; i < sourceNameElements.Count; ++i)
{
    targetNamesElements[i].SetValue(sourceNameElements[i].Value);
}

Console.WriteLine(targetDocument.ToString());

I don't know the easiest way to solve this ,this is best way I can think out,and you must ensure Name.count is larger than FirstName.count:

        var sourceXml =XElement.Parse(source);
        var targetXml = XElement.Parse(target);
        var i = 0;
        var nameArray = (from name in sourceXml.Descendants("Name")
            select  name.Value).ToArray();
        foreach (var fName in targetXml.Descendants("FirstName"))
        {
            fName.Value = nameArray[i++];
        }

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.

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