简体   繁体   中英

Update xDoc with same element name with No attributes

My XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
  <Properties>
   <Ranges>
    <GridRange>
     <ColumnID>991</ColumnID>
     <LowerBound>30</LowerBound>
     <UpperBound>59</UpperBound>
    </GridRange>
    <GridRange>
     <ColumnID>991</ColumnID>
     <LowerBound>60</LowerBound>
     <UpperBound />
    </GridRange>
   </Ranges>
 </Properties>

I want to update the value of the element (when it is 991) within to 1000. My code updating only the first to 1000 and not the second one.

 XElement columnID = xProperty.Root.Elements("Ranges").Elements("GridRange").Elements("ColumnID").FirstOrDefault();
 if (null != columnID && Convert.ToInt64(columnID.Value) == 991)  
    columnID.Value = "1000";

But I want both ColumnID element value to be 1000. How do i achieve this.

Try the code below to iterate through all GridRange elements and evaluate the ColumnID element's value.

Int64 columnID = Int64.MinValue;
foreach (var xElem in xProperty.Descendants("GridRange"))
{
    columnID = Int64.MinValue;
    var elem = xElem.Element("ColumnID");
    if (elem == null || !Int64.TryParse(elem.Value, out columnID) || columnID != 991)
        continue;
    elem.Value = "1000"; 
}

Now are you sure you need an Int64 as opposed to a Int32 ? Are the ColumnID values likely to exceed 2,147,483,647 ?

EDIT - Without conversions

If there is no need for conversions this code gets really easy and shorted.

foreach (var xElem in xProperty.Descendants("GridRange").Elements("ColumnID").Where(x => x.Value.Equals("991")))
            xElem.Value = "1000";

That's because you're using FirstOrDefault . For achieving what you want, do as follows:

xDoc.Root.Elements("Ranges")
         .Elements("GridRange")
         .Elements("ColumnID")
         .Where(xe => xe.Value == "991")
         .ToList()
         .ForEach(el => el.Value = "1000");

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