c# - 从 XDocument 获取元素并编辑属性

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

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

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

最佳答案

你可以尝试这样:

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

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

关于c# - 从 XDocument 获取元素并编辑属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26478152/

相关文章:

c# - 转换 Web API 以使用自托管

c# - 报告表格未在 VS 2013 中显示

c# - PHP/Rails/Django/ASP 网站应该是用 C++ 写的吧?

javascript - Webgl FTP错误

c# - 如何获取特定节点的值

c# - Linq to XML 使用 Take() 获取前两个元素

c# - 在 Windows Phone 8 中控制后退键

sql - 将巨大的复杂 XML 解析/切碎到 SQL Server 2008 数据库(30 多个表)

android - 如何将菜单项动态添加到抽屉导航?

.net - 使用linq2xml订购xml文件