簡體   English   中英

更改XML c#中最后一個屬性的值

[英]Change Value of the last Attribute in an XML c#

我正在處理一堆XML,它們都共享一個包含字符串“ name”的屬性。 以下代碼選擇其中帶有字符串“ name”的屬性,並為其分配一個新值。

        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); }
    }

現在,添加了一個新的XML,該XML中沒有字符串“ name”,所以我決定只修改最后一個屬性,而不是使用字符串“ name”來修改屬性(而不是第一個)。

有人可以告訴我該怎么做嗎?

編輯

這是我的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:您注意到“ SunSpots”屬性(第一個子元素中的最后一個屬性)已成功更改。 但是現在當我想將XML加載回數據庫時,它給了我一個錯誤

這是修改后的代碼

    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); }
    }

我正在考慮制作一個if語句,以檢查XML是否具有包含字符串“名稱”的屬性(因為我的大多數XML具有包含名稱的屬性),如果不這樣做,則更改該屬性的值最后一個屬性並更改它..不是最好的解決方案,只是將其扔在那里

我沒有測試過,但是您應該能夠在XPath表達式中完成所有這些操作。 像這樣的東西:

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

這將僅返回最后一個屬性,該屬性的name任意位置都有字符串名稱。

如果只希望最后一個屬性,無論其名稱如何,請使用以下命令:

//@*[last()]

然后一定要使用Linq到XML。 例:

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 ^

即,逐個單詞,第一個元素的第一個孩子的最后一個屬性。

您還可以查詢元素/屬性名稱,例如:

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

當然,您可以使用所有Linq優點,例如Where,Select,Any,All等。

注意:如果合適,請用XDocument.Load替換XDocument.Parse。

查看類XmlAttributeCollection 您可以通過閱讀XmlNode的屬性Attributes獲得此集合。 只需按索引獲取最后一個。

代替.First() ,使用如下擴展方法:

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

  return val;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM