【发布时间】: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