【问题标题】:Add Namespace to xml file将命名空间添加到 xml 文件
【发布时间】:2012-07-24 06:01:44
【问题描述】:

我有一个要添加预定义名称规范的 xml 文件。以下是代码:

private const string uri = "http://www.w3.org/TR/html4/";
private static readonly List<string> namespaces = new List<string> { "lun" };

public static XElement AddNameSpaceAndLoadXml(string xmlFile) {
    var nameSpaceManager = new XmlNamespaceManager(new NameTable());
    // add custom namespace to the manager and take the prefix from the collection
    namespaces.ToList().ForEach(name => {
         nameSpaceManager.AddNamespace(name, string.Concat(uri, name));
    });

    XmlParserContext parserContext = new XmlParserContext(null, nameSpaceManager, null, XmlSpace.Default);
    using (var reader = XmlReader.Create(@xmlFile, null, parserContext)) {
        return XElement.Load(reader);
    }
}

问题是内存中生成的 xml 没有显示添加的正确命名空间。此外,它们不会添加到根目录,而是添加到标签旁边。下面添加了 Xml。 在 xml 中它显示 p3:read_data 而应该是 lun:read_data

如何在根标签上添加命名空间而不是得到错误的名称。

示例输入 xml:

<config file-suffix="perf">
 <overview-graph title="Top 5 LUN Reads" max-series="5" remove-series="1">
  <counters lun:read_data=""/>
 </overview-graph>
</config>

预期输出 xml:

<config file-suffix="perf" xmlns:lun="http://www.w3.org/TR/html4/lun">
 <overview-graph title="Top 5 LUN Reads" max-series="5" remove-series="1">
  <counters lun:read_data=""  /> 
 </overview-graph>
</config>

使用上述代码的输出:

<config file-suffix="perf" >
 <overview-graph title="Top 5 LUN Reads" max-series="5" remove-series="1">
  <counters p3:read_data=""  xmlns:p3="http://www.w3.org/TR/html4/lun"/> 
 </overview-graph>
</config>

【问题讨论】:

  • 我不清楚你真正想要做什么。您已经展示了“示例 XML”,但它是输入还是输出并不明显。请显示示例输入和所需的输出。不用XmlNamespaceManager,你绝对可以做到这一点。
  • 你写namespaces.ToList().Foreach...命名空间的原因已经是一个问题,所以你可以写namespaces.Foreach...
  • 更新了输入输出xml和使用代码生成的xml..

标签: c# add xml-namespaces


【解决方案1】:

我不确定是否有更好的方法,但手动添加命名空间似乎可行。

using (var reader = XmlReader.Create(@xmlFile, null, parserContext)) {
    var newElement = XElement.Load(reader);
    newElement.Add(new XAttribute(XNamespace.Xmlns + "lun", string.Concat(uri, "lun")));
    return newElement;
}

不过,我不知道有一种方法可以概括这一点(显然,您可以通过枚举它来添加整个集合,但只输出使用过的命名空间可能会很有趣)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2017-09-21
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    相关资源
    最近更新 更多