从XDocument&获取元素编辑属性

时间:2014-10-21 02:50:53

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

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

我试图提取这个

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

并将PromotionId =“5200”转换为PromotionId =“XXX”

我可以提取&lt;促销&gt;具有以下代码的元素,但无法解决如何更改属性

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

2 个答案:

答案 0 :(得分:1)

您可以尝试这种方式:

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

使用简单的XNamespace + local-name引用命名空间中的元素。然后,您可以使用.Attribute()方法从XAttribute获取XElement并更改属性的值。

答案 1 :(得分:0)

试一试:它会返回 Promotion 标记中所有属性的值。

 XNamespace ns1 = XNamespace.Get("http://fake.com/services");
 var readPromotion = from a in xx.Descendants(ns1 + "Promotion")
                            select new
                            {
                                PromotionID = (string)a.Attribute("PromotionId"),
                                EffectiveDate = (string)a.Attribute("EffectiveDate"),
                                ExpirationDate = (string)a.Attribute("ExpirationDate"),
                                PromotionStatus = (string)a.Attribute("PromotionStatus"),
                                PromotionTypeName = (string)a.Attribute("PromotionTypeName"),
                                Description = (string)a.Value

                            };

        foreach (var read in readPromotion)
        {
            // Read values
        }