【问题标题】:How to save attribute value on xml file?如何在xml文件中保存属性值?
【发布时间】:2019-05-27 04:35:46
【问题描述】:

我正在尝试在我的 xml 文件中保存一个值。在下面的代码中,行“s.Attribute("Value").Value = value; break;"执行并保存文件,但不会更改属性的值

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

【问题讨论】:

  • 您正在将 xml 文件加载到 doc,但随后您将其单独加载到 elements,更改 elements,然后保存 doc。你需要选择一个。

标签: c# xml linq-to-xml


【解决方案1】:

实际上有两件事可能会有所不同。

a) 您正在使用 XDocument.Load 和 XElement.Load 读取 Xml。修改时使用的是 Elements,保存时使用的是 XDocument。

b) 由于 XML 中的层次结构是 (Items.Item),因此最好使用 Descendants 来解析元素。

完整代码

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

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    相关资源
    最近更新 更多