【问题标题】:C# CreateElement method - how to add an child element with xmlns=""C# CreateElement 方法 - 如何使用 xmlns="" 添加子元素
【发布时间】:2011-02-15 08:00:09
【问题描述】:

如何获取以下代码以添加带有“xmlns=''”的元素?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml; 

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string strXML = 
                "<myroot>" + 
                "   <group3 xmlns='myGroup3SerializerStyle'>" + 
                "       <firstname xmlns=''>Neal3</firstname>" + 
                "   </group3>" + 
                "</myroot>";

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(strXML);

            XmlElement elem = xmlDoc.CreateElement(null, "lastname", null);
            elem.InnerText = "New-Value";

            string strXPath = "/myroot/*[local-name()='group3' and namespace-uri()='myGroup3SerializerStyle']/firstname";
            XmlNode insertPoint = xmlDoc.SelectSingleNode(strXPath);
            insertPoint.AppendChild(elem);

            string resultOuter = xmlDoc.OuterXml;

            Console.WriteLine("\n resultOuter=" + resultOuter);

            Console.ReadLine(); 

        }
    }
}

我目前的输出:

 resultOuter=<myroot><group3 xmlns="myGroup3SerializerStyle"><firstname xmlns=""
>Neal3<lastname>New-Value</lastname></firstname></group3></myroot>

想要的输出:

 resultOuter=<myroot><group3 xmlns="myGroup3SerializerStyle"><firstname xmlns=""
>Neal3<lastname xmlns="">New-Value</lastname></firstname></group3></myroot>

有关背景,请参阅相关帖子: http://www.stylusstudio.com/ssdn/default.asp?fid=23(今天)

.NET XmlSerializer to Element FormDefault=Unqualified XML?(3 月 9 日,以为我修好了,今天又咬我了!)

【问题讨论】:

    标签: c# xml xmldocument


    【解决方案1】:

    糟糕——没关系。

    我将 XPath 更改为:

    string strXPath = "/myroot/*[local-name()='group3' and namespace-uri()='myGroup3SerializerStyle']";
    

    它奏效了。 想法是将姓氏添加到与名字相同的级别,而不是在名字下。

    正确的期望输出是这样的:

    resultOuter=<myroot><group3 xmlns="myGroup3SerializerStyle"><firstname xmlns=""
    >Neal3</firstname><lastname xmlns="">New-Value</lastname></group3></myroot>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 2021-03-26
      • 2013-12-03
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      相关资源
      最近更新 更多