【问题标题】:Editing XML Attribute Causes a new node to be created编辑 XML 属性会导致创建一个新节点
【发布时间】:2013-01-08 21:44:33
【问题描述】:

当我尝试更新我的 XML 文档中的值时,它不会编辑现有值,而是不断插入一个带有我的新值的新节点。

如果尝试了这两种方法,结果相同......

var doc = XDocument.Parse(xmlString);

XElement shippingElement = (from xml2 in doc
  .Elements("extradata").Elements("SharedCustomAppData")
  .Elements("clsNameValues").Elements("clsnamevalue")
where xml2.Element("name").Attribute("Value").Value == "SHOP_FLOOR_INSTR"
select xml2).FirstOrDefault();

shippingElement.Element("value").Attribute("Value").Value = "Changed!";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(oLine.ExtraData);
XmlNodeList nodes = xmlDoc.SelectNodes(
   "extradata/SharedCustomAppData/clsNameValues/clsnamevalue");

foreach (XmlNode node in nodes)
{
XmlNode nameNode = node.SelectSingleNode("name");

if (nameNode != null && nameNode.Attributes["Value"].Value == "SHOP_FLOOR_INSTR")
{
    XmlNode valueNode = node.SelectSingleNode("value");

    if (valueNode != null)
    {
        valueNode.Attributes["Value"].Value = line.SHOP_FLOOR_INSTR;
    }
}
}

我尝试更新的 XML 部分如下所示:

  <SharedCustomAppData>
   <clsNameValues>
     <clsnamevalue>
       <name Value="SHOP_FLOOR_INSTR" />
       <value Value="Current value" />
     </clsnamevalue>
   </clsNameValues>
 </SharedCustomAppData>

【问题讨论】:

  • 您的 Linq to Xml 代码在此 xml 上运行良好。你能用 extradata 元素显示整个 xml 吗?

标签: c# xml linq-to-xml xmldocument


【解决方案1】:

赋值语句中元素名称不应该是“name”而不是“value”吗?

试试这个:

var doc = XDocument.Parse(xmlString);

XElement shippingElement = (from xml2 in doc
   .Elements("extradata").Elements("SharedCustomAppData")
   .Elements("clsNameValues").Elements("clsnamevalue")
where xml2.Element("name").Attribute("Value").Value == "SHOP_FLOOR_INSTR"
select xml2).FirstOrDefault();

shippingElement.Element("name").Attribute("Value").Value = "Changed!";

【讨论】:

  • 这实际上是价值。 value 是节点的名称,Value 是其中我必须更改的值。不是我会如何设计它,但它不是我可以改变的。
【解决方案2】:

您可以为 Linq to Xml 使用 System.Xml.XPath 扩展(我相信代码会看起来更短):

var expression = "//extradata/SharedCustomAppData/clsNameValues/clsnamevalue[name/@Value='SHOP_FLOOR_INSTR']/value";
XElement valueElement = xdoc.XPathSelectElement(expression);
if (valueElement != null)
    valueElement.SetAttributeValue("Value", "Changed!");

还要注意命名空间(如果在父节点上声明了一些命名空间,从您的示例 xml 中不清楚)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 2010-10-13
    • 1970-01-01
    • 2015-10-05
    相关资源
    最近更新 更多