Search code examples
c#.netxelement

Using XElement to edit attribute names


So I'm looking for a way to edit individual element descriptions in an XML file.

For example, say I have:

1  <stack id ="1">Stack1</stack>
2  <book id="EG-FE">This Book</book>
3  <book id="EG-FF">That Book</book>
4  <book id="FE-GT">Another Book</book>
5  <book id="JL-01">Invalid Book Id</book>
6  <stack id="2">Stack2</stack>

You'll notice the book on line 5 has an odd format... the second part of the id (after the '-') has numbers where the rest of them have letters. How would I go about removing just the '-01' part of the id of book 5 (I.e. change it to:

5  <book id="JL">Valid Book Id</book>

without modifying eny other elements? (I.E. stack)

Here is what I'm trying:

using System.Xml.Linq

XElement books = XElement.Load("{file}");

string _Attribute;
foreach (var bookID in books.Nodes()) 
{
    if(bookID.Attribute("book") )
    {
        _Attribute = bookID.Attribute("book")
        if(!Regex.IsMatch(_Attribute., @"^[a-zA-Z-]+$");
        {
            Regex.Replace(_Attribute, @"\d", "");
        }
        bookID.Attribute("book") = _Attribute;
    }
}

Obviously, this is horribly wrong... Any ideas on how to fix it?

Thank you!

I haven't found much help dealing directly with this problem, and the bits and pieces I'm trying to put together aren't really helping.


Solution

  • using System.Xml.Linq
    
    XElement books = XElement.Load("{file}");
    
    string _Attribute;
    foreach (var bookID in books.Elements("book")) 
    {
        if(bookID.Attribute("id") != null)
        {
            _Attribute = bookID.Attribute("book").Value;
            if(!Regex.IsMatch(_Attribute, @"-[0-9]+$"))
            {
                Regex.Replace(_Attribute, @"-[0-9]+$", "");
            }
            bookID.Attribute("id").Value = _Attribute;
        }
    }
    

    Untested and all those usual comments. Fixed some of your assumptions about how Linq to XML works, and made the Regex check see if it ends in a digit and replace the final digits in that case.