【问题标题】:How to add a namespace to specific attributes using linq?如何使用 linq 将命名空间添加到特定属性?
【发布时间】:2016-09-23 11:03:38
【问题描述】:

我们正在使用 NewtonSoft 的标准 .NET 功能从 XML 创建 JSON。我们知道我们需要使用命名空间来将值定义为数组,如@Json:Array="true",但是在从 SQL Server 返回 XML 时尝试使用命名空间时遇到了一些问题。

我们要做的是在 SQL Server Array="true" 中指定,然后对 XML 进行后处理以添加 @Json 命名空间前缀。

是否有一个 XElement 方法(可能使用 LINQ ?)我们可以一键完成,即将 JSON 命名空间前缀添加到所有名为 "Array" 的属性? 我们不希望将 XElement 转换为字符串并进行查找/替换(到目前为止我们已经对其进行了测试)或者必须对元素进行树遍历,因为我无法想象这会非常高效.

【问题讨论】:

  • 如果您提供 minimal reproducible example 会有所帮助 - 请注意,所有 JSON 和数据库部分几乎无关紧要,尽管将它们作为背景动机可能是合理的。
  • 绝对不需要转换成字符串,但是tree-walk会...

标签: .net json xml namespaces


【解决方案1】:

我相信你必须去树上散步。

如果您想保留所有属性,则需要使用XElement.ReplaceAttributes。否则,您可以删除旧的并添加新的。 (您不能修改XAttribute 的名称。)

示例代码:

using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        var xdoc = new XDocument(
            new XElement("root",
               new XElement("child1",
                   new XAttribute("NotArray", "foo"),
                   new XAttribute("Array", "bar")
               ),
               new XElement("child2",
                   new XAttribute("Array", 0),
                   new XAttribute("Y", 1)
               )
            )
        );
        Console.WriteLine("Before:");
        Console.WriteLine(xdoc);
        Console.WriteLine();

        XNamespace ns = "@Json";
        var attributesToReplace = xdoc
            .Descendants()
            .Attributes("Array")
            .ToList();
        foreach (var attribute in attributesToReplace)
        {
            var element = attribute.Parent;
            attribute.Remove();
            element.Add(new XAttribute(ns + "Array", attribute.Value));
        }
        Console.WriteLine("After:");
        Console.WriteLine(xdoc);
    }
}

输出:

Before:
<root>
  <child1 NotArray="foo" Array="bar" />
  <child2 Array="0" Y="1" />
</root>

After:
<root>
  <child1 NotArray="foo" p2:Array="bar" xmlns:p2="@Json" />
  <child2 Y="1" p2:Array="0" xmlns:p2="@Json" />
</root>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-21
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多