使用XDocument和XElement如何在C#中向XML添加XAttribute和值?

时间:2015-04-02 13:04:21

标签: c# xml

我想复制:

    <gcf>
        <cbxDecOnly Type="Boolean">False</cbxDecOnly>
        <cbxFormName Type="String" />
        <txtCustomerCellPhonePart2 Type="String">5236</txtCustomerCellPhonePart2>
        <txtCustomerCellPhonePart1 Type="String">533</txtCustomerCellPhonePart1>
        ....
    </gcf>
到目前为止,我有:

var xdoc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement("gcf",
    new XElement("cbxDecOnly", new XAttribute("Type", "Boolean")),
    new XElement("cbxFormName", oGSFE.TextBoxClientName),
    new XElement("txtCustomerCellPhonePart2", oGSFE.TextBoxDealSearch),
    new XElement("txtCustomerCellPhonePart1 ", oGSFE.DropDownListFIManager)
                )
            );

我不知道如何将XAttribute和值同时添加到XML元素<cbxDecOnly Type="Boolean">False</cbxDecOnly>

1 个答案:

答案 0 :(得分:3)

以同样的方式为txtCustomerCellPhonePart2等节点提供值 - 将字符串值包含为element's params content[]之一:

var xdoc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement("gcf",
    new XElement("cbxDecOnly", "False", new XAttribute("Type", "Boolean")),
    new XElement("cbxFormName", oGSFE.TextBoxClientName),
    new XElement("txtCustomerCellPhonePart2", oGSFE.TextBoxDealSearch),
    new XElement("txtCustomerCellPhonePart1", oGSFE.DropDownListFIManager)
    )
);

string中提供的content[]类型的任何值都将合并到元素的值中,类型XAttribute的任何值都将创建属性以及{{1}类型的任何值1}}将成为孩子。