C#中高效率移除XML命名空間宣告
本文提供一個全面的解決方案,用於從XML文件中移除命名空間聲明,簡化結構或滿足特定需求。
問題:
您希望移除XML文件中的所有命名空間聲明,以簡化其結構或滿足特定要求。
介面:
<code class="language-csharp">public interface IXMLUtils { string RemoveAllNamespaces(string xmlDocument); }</code>
範例XML:
<code class="language-xml"><?xml version="1.0" encoding="utf-16"?><arrayofinserts xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><insert><offer xmlns="http://schema.peters.com/doc_353/1/Types">0174587</offer><type2 xmlns="http://schema.peters.com/doc_353/1/Types">014717</type2><supplier xmlns="http://schema.peters.com/doc_353/1/Types">019172</supplier><id_frame xmlns="http://schema.peters.com/doc_353/1/Types"></id_frame><type3 xmlns="http://schema.peters.com/doc_353/1/Types"><type2></type2><main>false</main></type3><status xmlns="http://schema.peters.com/doc_353/1/Types">Some state</status></insert></arrayofinserts></code>
預期輸出:
<code class="language-xml"><?xml version="1.0" encoding="utf-16"?><arrayofinserts><insert><offer>0174587</offer><type2>014717</type2><supplier>019172</supplier><id_frame></id_frame><type3><type2></type2><main>false</main></type3><status>Some state</status></insert></arrayofinserts></code>
解:
可以使用遞歸函數遍歷XML文件並從所有元素中移除命名空間。函數遵循以下步驟:
以下是解決方案的C#實作:
<code class="language-csharp">public static string RemoveAllNamespaces(string xmlDocument) { XElement xmlDocumentWithoutNamespaces = RemoveAllNamespaces(XElement.Parse(xmlDocument)); return xmlDocumentWithoutNamespaces.ToString(); } private static XElement RemoveAllNamespaces(XElement xmlDocument) { if (!xmlDocument.HasElements) { XElement xElement = new XElement(xmlDocument.Name.LocalName); xElement.Value = xmlDocument.Value; foreach (XAttribute attribute in xmlDocument.Attributes()) xElement.Add(attribute); return xElement; } return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el))); }</code>
此解決方案全面且健壯,可以有效地處理葉子元素和非葉子元素。它還保留了XML元素的原始值和屬性,確保可靠且準確地移除命名空間。
以上是如何在 C# 中高效率刪除 XML 命名空間聲明?的詳細內容。更多資訊請關注PHP中文網其他相關文章!