2012-07-24 101 views
2

我有一個XML文件,而我要添加預定義的namespeces ..以下是代碼:命名空間添加到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> 
+0

我不清楚你真的想要做什麼。你已經展示了「示例XML」,但不知道它是輸入還是輸出。請顯示示例輸入和所需輸出。你絕對可以做到這一點,而不使用'XmlNamespaceManager'。 – 2012-07-24 06:05:05

+0

爲什麼寫'namespaces.ToList()。foreach ...'''''''''''''''命名空間已經很不錯了,所以你可以寫'namespaces.Foreach ...' – harry180 2012-07-24 06:16:53

+0

更新了輸入,輸出xml和使用代碼生成的xml。 – Arihant 2012-07-24 06:33:43

回答

0

我不知道是否有更好的方法,但手動添加名稱空間似乎工作。

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; 
} 

我不知道隨便的方式但概括這個(很明顯,你可以通過枚舉它添加了一整套,但只輸出使用的命名空間可能是有趣)。