简体   繁体   English

如何在xml文件中保存属性值?

[英]How to save attribute value on xml file?

I'm trying to save a value in my xml file. 我正在尝试在我的xml文件中保存一个值。 In the code below, the line "s.Attribute("Value").Value = value; break;" 在下面的代码中,行“s.Attribute(”Value“)。Value = value; break;” executes and the file is saved but it doesn't change the value of the attribute 执行并保存文件,但不会更改属性的值

在此输入图像描述

     public void CustomSettingXML_WriteValue(string key, string value)
    {

        XDocument doc = XDocument.Load(xmlFile);

        var elements = from x in XElement.Load(xmlFile).Elements("Item") select x;

        foreach (var s in elements)
        {
            if (s.Attribute("Text").Value == key)
            {
                s.Attribute("Value").Value = value; 
                doc.Save(@xmlFile);                    
               break;
            }
        }
    }

There are in fact two things that might have to vary. 事实上有两件事可能会有所不同。

a) You are reading the Xml using XDocument.Load as well as XElement.Load. a)您正在使用XDocument.Load和XElement.Load读取Xml。 While altering, you are using Elements, and while saving you are using XDocument. 在更改时,您正在使用Elements,而在保存时您正在使用XDocument。

b) Since hierarchy in XML is (Items.Item), it would be better you use Descendants to parse the elements. b)由于XML中的层次结构是(Items.Item),因此最好使用Descendants来解析元素。

Full Code 完整代码

public void CustomSettingXML_WriteValue(string key, string value)
{
    XDocument doc = XDocument.Load(xmlFile);
    var elements = from x in doc.Descendants("Item") select x;
    foreach (var s in elements)
    {

        if (s.Attribute("Text").Value == key)
        {
            s.Attribute("Value").Value = value; 
            doc.Save(@xmlFile);                    
           break;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM