从 XDocument 和 Edit 属性获取元素

本文关键字:获取 元素 属性 Edit XDocument | 更新日期: 2023-09-27 18:27:10

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

我可以使用以下代码提取<促销>元素,但无法弄清楚如何更改属性

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

从 XDocument 和 Edit 属性获取元素

你可以试试这种方式:

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

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

试试这个: 它返回促销代码中所有属性的值。

 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
        }