tags:

views:

70

answers:

4

I was working on a bunch of XMLs that all share an attribute that contains the string "name" in them. The following code selects the attribute with string "name" in it and assign a new value to it.

        public void updateXmlFile(string strFileName)
    {
        try
        {
            //Load the Document
            XmlDocument doc = new XmlDocument();
            doc.Load(strFileName);
            //Set the changed Value
            string newValue = GetUniqueKey();
            //Select all nodes in the XML then choose from them
            //the first node that contain string "name" in it
            XmlNodeList list = doc.SelectNodes("//@*");
            XmlNode filteredNode = list.Cast<XmlNode>()
                .First(item => item.Name.ToLower().Contains("name"));
            //Assign the newValue to the value of the node
            filteredNode.Value = newValue;

            doc.Save(strFileName);
        }
        catch (XmlException xex) { Console.WriteLine(xex); }
    }

Now a new XMLs were added that dosen't have the string "name" in them, so instead of modifying the attribute with string "name" in it I decided to simply modify the last attribute no matter what it was (not the first)

Can anybody tell me how to do that?

EDIT

Here is an example of my XML

<?xml version="1.0" encoding="utf-8"?>
<CO_CallSignLists Version="24" ModDttm="2010-09-13T06:45:38.873" ModUser="EUADEV\SARE100" ModuleOwner="EUADEVS06\SS2008" CreateDttm="2009-11-05T10:19:31.583" CreateUser="EUADEV\A003893">
  <CoCallSignLists DataclassId="E3FC5E2D-FE84-492D-AD94-3ACCED870714" EntityId="E3FC5E2D-FE84-492D-AD94-3ACCED870714" MissionID="4CF71AB2-0D92-DE11-B5D1-000C46F3773D" BroadcastType="S" DeputyInSpecialList="1" SunSpots="1537634cb70c6d80">
    <CoCallSigns EntityId="DEBF1DDB-3C92-DE11-A280-000C46F377C4" CmdID="C45F3EF1-1292-DE11-B5D1-000C46F3773D" ModuleID="6CB497F3-AD63-43F1-ACAE-2C5C3B1D7F61" ListType="HS" Name="Reda Sabassi" Broadcast="INTO" PhysicalAddress="37" IsGS="1" HCId="0" CommonGeoPos="1" GeoLat="0.0000000" GeoLong="0.0000000">
      <CoRadios EntityId="E1BF1DDB-3C92-DE11-A280-000C46F377C4" RadioType="HF" />
    </CoCallSigns>
  </CoCallSignLists>
</CO_CallSignLists>

@Alex: You notice that the "SunSpots" attribute (last attribute in the first child element) is successfully changed. But now when I wanna load the XML back into the DB it gives me an error

Here is the modified code

    public void updateXmlFile(string strFileName)
    {
        try
        {
            XDocument doc = XDocument.Load(strFileName);

            XAttribute l_attr_1 = (doc.Elements().First().Elements().First().Attributes().Last());
            l_attr_1.Value = GetUniqueKey();

            Console.WriteLine("Name: {0}  Value:{1}", l_attr_1.Name, l_attr_1.Value);

            doc.Save(strFileName);
        }
        catch (XmlException xex) { Console.WriteLine(xex); }
    }

I was thinking of making an if statment which checks if the XML has an attribute that contains string "name" in it (since most of my XMLs has an attribute that contains name in them) if it does then change the attribute's value if not look for the last attribute and change it.. not the best solution but just throwing it out there

A: 

Look at class XmlAttributeCollection. You can get this collection by reading property Attributes of XmlNode. Just get the last by index.

archer
A: 

Instead of .First(), use an extension method like this:

public static T LastOrDefault<T>(this IEnumerable<T> list)
{
  T val = null;
  foreach(T item in list)
  {
     val = item;
  }

  return val;
}
Hans Kesting
+1  A: 

I've not tested this but you should be able to do all of this in the XPath expression. Something like this:

//@*[contains(node-name(.), 'name')][last()]

This will return only the last attribute with the string name anywhere in its name.

If you only want the last attribute, irrespective of it's name, use this:

//@*[last()]
Daniel Renshaw
This worked just fine. But now I figuerd I want the last attribute of the first child. I'll add an example of my XML in the main Post, Your code changes the CreatUser attribute where I want is to change ony the Remark attribute
Reda
+1  A: 

Then definitely use Linq to XML. Example:

using System.Xml.Linq;

string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Commands Version=""439""  CreateUser=""Reda"">
  <CmCommands DataclassId=""57067ca8-ef96-4d2e-a085-6bd7e8b24126"" OrderName = ""Tea"" Remark=""Black"">
    <CmExecutions EntityId=""A9A5B0F2-6AB4-4619-9106-B0F85F86EE01"" Lock=""n"" />
  </CmCommands>
</Commands>";

XDocument x = XDocument.Parse(xml);

Debug.Print(x.Elements().First().Elements().First().Attributes().Last().Value);
//                 Commands ^      CmCommands ^             Remark ^

That is, word for word, the last attribute of the first child of the first element.

You can also query for element/attribute names, like:

Debug.Print(x.Descendants(XName.Get("CmCommands", "")).First().Attribute(XName.Get("Remark", "")).Value);

And of course you can use all of the Linq goodness like Where, Select, Any, All etc.

Note: replace XDocument.Parse with XDocument.Load if appropriate etc.

Alex Paven
thx Alex it works :) only that now I have the problem that some XMLs have Last Attributes as smallint type and can't be stored in the DB as strings.. any ideas on how to modify these attributes?
Reda
Well, all values in XML are strings by default, and not automatically converted; you'll either need to convert manually (e.g. `int.Parse(value)`) or transform the entire XML tree into objects; if you're using most of the values in the XML, that's definitely the way to go, let me know if you need more help and I'll edit my answer.
Alex Paven
the problem is not changing the value of the attribute but in saving it back into the DB..the value is successfully modified but when I wanna store it back into the DB it gives me an error (all the XMLs I'm modifying are DB Tables and rows
Reda
So what are you using to save it back then? Can't say I've seen this technique before :) I'd think it would be fine as long as you don't change values to an incompatible type, which probably means you'll need the schema and validate your final XML, or as I said, turn it into objects (classes) first, which will enforce the constraints.
Alex Paven
what I'm doing is retrieving Tables from DB and saving them into XML files then I modify these XMLs and load the modified XML back into the DB. Now the problem is with this particuler XML the last attribute is a of type smallint in the DB and when I modify its value I modify it to a string, so when I load it back it gives me an error "Conversion failed when converting the nvarchar value (my new value) to data type smallint." Error #=245
Reda
Ouch. I'd strongly recommend you don't do that. Why not modifying the tables directly using specific techniques of ADO.Net? Anyway, I'm sure there's a reason for that, but in that case... as I said, attribute and element values are stored as strings anyway, but they may also have additional metadata that defines what types they should be converted into. The data table schema is a pretty complex one I think, can you post a relevant snippet of elements containing the problem attributes?
Alex Paven
check my original Post.. I'll modify the xml into the one I#m having problems with
Reda