首頁 > 後端開發 > C++ > 如何在 C# 中高效率刪除 XML 命名空間聲明?

如何在 C# 中高效率刪除 XML 命名空間聲明?

Linda Hamilton
發布: 2025-01-23 22:44:13
原創
624 人瀏覽過

How Can I Efficiently Remove XML Namespace Declarations in C#?

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文件並從所有元素中移除命名空間。函數遵循以下步驟:

  1. 對於葉子元素(沒有子元素的元素),建立一個具有原始元素的局部名稱和值的新元素,並複製任何屬性。
  2. 對於具有子元素的元素,建立一個具有原始元素局部名稱的新元素,並對每個子元素遞歸呼叫函數。

以下是解決方案的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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板