c# - 如何使用linq xml将命名空间添加到xml

标签 c# xml linq xml-namespaces

问题更新:如果我的问题不清楚,我非常抱歉

这是我现在使用的代码

XDocument doc = XDocument.Parse(framedoc.ToString());
foreach (var node in doc.Descendants("document").ToList())
{
    XNamespace ns = "xsi";
    node.SetAttributeValue(ns + "schema", "");
    node.Name = "alto";
}

这是输出

<alto p1:schema="" xmlns:p1="xsi">

我的目标是这样的

xsi:schemaLocation=""

p1xmlns:p1="xsi" 从何而来?

最佳答案

当你写作时

XNamespace ns = "xsi";

这就是创建一个只有“xsi”的 URI 的 XNamespace。那不是你想要的。您需要 xsi 的命名空间 alias... 通过 xmlns 属性使用适当的 URI。所以你想要:

XDocument doc = XDocument.Parse(framedoc.ToString());
foreach (var node in doc.Descendants("document").ToList())
{
    XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
    node.SetAttributeValue(XNamespace.Xmnls + "xsi", ns.NamespaceName);
    node.SetAttributeValue(ns + "schema", "");
    node.Name = "alto";
}

或者更好的是,只需在根元素上设置别名:

XDocument doc = XDocument.Parse(framedoc.ToString());
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
doc.Root.SetAttributeValue(XNamespace.Xmlns + "xsi", ns.NamespaceName);
foreach (var node in doc.Descendants("document").ToList())
{
    node.SetAttributeValue(ns + "schema", "");
    node.Name = "alto";
}

创建文档的示例:

using System;
using System.Xml.Linq;

public class Test
{
    static void Main()
    {
        XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
        XDocument doc = new XDocument(
            new XElement("root",
                new XAttribute(XNamespace.Xmlns + "xsi", ns.NamespaceName),
                new XElement("element1", new XAttribute(ns + "schema", "s1")),
                new XElement("element2", new XAttribute(ns + "schema", "s2"))
            )                         
        );
        Console.WriteLine(doc);
    }
}

输出:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <element1 xsi:schema="s1" />
  <element2 xsi:schema="s2" />
</root>

关于c# - 如何使用linq xml将命名空间添加到xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41136088/

相关文章:

c# - 是否可以在编辑器进入 Unity 播放模式之前将场景更改为加载?

c# - 如何使用 Dapper 连接到 ProgressDB 数据提供程序?

php - Codeigniter RESTful API 服务器 - XML 错误?

c# - 有没有更好的方法来设置 linq 中项目列表的公共(public)属性

c# - 删除可选的最后一个括号

c# - 在跨平台 (Xamarin) 应用程序中使用哪个 IoC 容器?

c# - XML 解析错误 - C#

android - 您是否已在 AndroidManifest.xml 中声明此 Activity ?

c# - 将 IEnumerable<X> 转换为 List<Y>

c# - 我可以一次合并这两个列表吗