Search code examples
c#xmllinq-to-xmlxelement

Get Element from XDocument & Edit Attribute


<GetPromotionByIdResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" MajorVersion="2" xmlns="http://fake.com/services">
    <Header>
        <Response ResponseCode="OK">
            <RequestID>1</RequestID>
        </Response>
    </Header>
    <Promotion PromotionId="5200" EffectiveDate="2014-10-10T00:00:00" ExpirationDate="2014-11-16T23:59:00" PromotionStatus="Active" PromotionTypeName="DefaultPromotion">
        <Description TypeCode="Long" Culture="en-AU">Promotion Description</Description>
    </Promotion>
</GetPromotionByIdResponse>

Im trying to extract this

<Promotion PromotionId="5200" EffectiveDate="2014-10-10T00:00:00" ExpirationDate="2014-11-16T23:59:00" PromotionStatus="Active" PromotionTypeName="DefaultPromotion">
        <Description TypeCode="Long" Culture="en-AU">Promotion Description</Description>
    </Promotion>

and convert the PromotionId="5200" to PromotionId="XXX"

I can extract the < Promotion > element with the below code but cant work out how to change the attribute

XNamespace xmlResponseNamespace = xmlPromotionResponse.Root.GetDefaultNamespace();

        XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());
        nsm.AddNamespace("def", xmlResponseNamespace.ToString());

        XElement xmlPromotionElement =
            xmlPromotionResponse
            .Descendants().SingleOrDefault(p => p.Name.LocalName == "Promotion");

Solution

  • You can try this way :

    XNamespace ns = "http://fake.com/services";
    XElement xmlPromotionElement = xmlPromotionResponse.Descendants(ns+"Promotion")
                                                       .SingleOrDefault();
    xmlPromotionElement.Attribute("PromotionId").Value = "XXX";
    

    Use simple XNamespace + local-name to reference an element in namespace. Then you can use .Attribute() method to get XAttribute from an XElement and change the attribute's value.