0

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.

gfppaste
  • 1,111
  • 4
  • 18
  • 48

2 Answers2

2
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.

Guvante
  • 18,775
  • 1
  • 33
  • 64
  • So I'm having a lot of trouble figuring out how to get just the element name... all the help I can find is to get the contents of the element. How would I just get ? – gfppaste May 17 '12 at 20:42
  • @gfppaste: `bookID` in my example is an `XElement` that contains `Title`. – Guvante May 17 '12 at 20:44
  • Ohhhh okay, I get it now. Haha thanks, I needed that mental shove! – gfppaste May 17 '12 at 20:45
0
string strHtml = "<input Type=\"Text\" Name=\"Initial Name Value\" Id=\"ID Value\" />";
XElement root = XElement.Parse(strHtml); // Carrega o Bicho...

root.SetAttributeValue("ValueA", 1); // New Attribute - Int Value

root.SetAttributeValue("ValueC", 3); // New Attribute - Int Value
root.SetAttributeValue("ValueC", null); // Remove Attribute

root.SetAttributeValue("ValueA", "New value for ValueA");

root.SetAttributeValue("Name", "New Name"); // Alterando Value propriedade recebida no Parse()

Console.WriteLine(root);