Tim Morford
Tim Morford

Reputation: 101

Using XDocument and XElement how do I add a XAttribute and a value to XML in C#

I am trying to replicate:

    <gcf>
        <cbxDecOnly Type="Boolean">False</cbxDecOnly>
        <cbxFormName Type="String" />
        <txtCustomerCellPhonePart2 Type="String">5236</txtCustomerCellPhonePart2>
        <txtCustomerCellPhonePart1 Type="String">533</txtCustomerCellPhonePart1>
        ....
    </gcf>

so far I have:

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

what I don't know is how to add a XAttribute and a value at the same time to the XML element <cbxDecOnly Type="Boolean">False</cbxDecOnly>

Upvotes: 1

Views: 465

Answers (1)

GSerg
GSerg

Reputation: 78190

In the same way you provide the value for your txtCustomerCellPhonePart2 etc nodes - by including the string value as one of the 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)
    )
);

Any values of type string provided in content[] will be merged into the element's value, any values of type XAttribute will create attributes and any values of type XElement will become the children.

Upvotes: 3

Related Questions