繁体   English   中英

如何使用C#添加XMl节点属性?

[英]How a add a XMl node attributes using C#?

我需要在XML文件中添加以下XML节点。

<preference name='phonegap-version' value='cli-5.1.1' />

但是我越来越像

<preference name="'phonegap-version' value='cli-5.1.1'" xmlns="" />

我在C#中使用了以下代码。

XmlElement preference = doc.CreateElement("preference");
root.AppendChild(preference);
XmlAttribute newAttribute = doc.CreateAttribute("name");
newAttribute.Value="'phonegap-version' value='cli-5.1.1'";
preference.Attributes.Append(newAttribute);

你能解决吗? 提前致谢...

问题是您只创建一个属性(称为name ),然后尝试用多个属性填充它。 您仅附加该单个属性。 相反,您应该创建两个属性并附加每个属性。

XmlElement preference = doc.CreateElement("preference");
root.AppendChild(preference);

// create and append the attribute 'name'
XmlAttribute attributeName = doc.CreateAttribute("name");
attributeName.Value = "phonegap-version";
preference.Attributes.Append(attributeName);

// create and append the attribute 'value'
XmlAttribute attributeValue = doc.CreateAttribute("value");
attributeValue.Value = "cli-5.1.1";
preference.Attributes.Append(attributeValue);

使用XDocument,您可以尝试以下操作:

XDocument doc = XDocument.Load("doc.xml");
XElement el = new XElement("preference", new Object[] {new XAttribute("name", "phonegap-version"), new XAttribute("value", "cli-5.1.1")});
doc.Add(el);
doc.Save("doc.xml");

我发现System.Xml.Linq更易于使用。 尝试这个:

        XDocument doc = XDocument.Load("yourpath.xml");
        XElement root = doc.Root;
        root.Add(new XElement("preference",
            new XAttribute("name", "'phonegap-version'"),
            new XAttribute("value", "'cli-5.1.1'")));
        doc.Save("yourpath.xml");
foreach (XmlNodenode in preferance)
{

    // if element already there, it will override
    XmlAttribute newAttr = xdoc.CreateAttribute("value");
    newAttr.Value = "cli-5.1.1";
    node.Attributes.Append(newAttr);
}

暂无
暂无

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

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