将新属性添加到MemoryStream XML

时间:2013-01-02 20:25:53

标签: c# xml xml-namespaces

我想添加

xsi:noNamespaceSchemaLocation="FullModeDataset.xsd"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

作为对我的根节点的响应" ApplicationData"所以根节点看起来像这样..

 <ApplicationData
  xsi:noNamespaceSchemaLocation="FullModeDataset.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />

我正在从字符串创建xml,使用此代码输出一个适当的xml字符串..

var doc = new XmlDocument();
            doc.LoadXml(myInputXmlString);
            var ms = new MemoryStream();
            var tx = XmlWriter.Create(ms,
                        new XmlWriterSettings
                        {
                            OmitXmlDeclaration = false,
                            ConformanceLevel = ConformanceLevel.Document,
                            Encoding = UTF8Encoding.UTF8
                        });
            doc.Save(tx);

              //I TRIED THE COMMENTED CODE BELOW BUT WITH NO SUCCESS
             //XmlAttribute newAttr = doc.CreateAttribute("xsi:noNamespaceSchemaLocation");
             //newAttr.Value = "FullModeDataset.xsd";

            //XmlElement applicationNode = doc.DocumentElement["AppicationData"];
            //applicationNode.Attributes.Append(newAttr);
            //doc.Save(tx);

            var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());

如何将这些属性添加到我的xml字符串?

1 个答案:

答案 0 :(得分:5)

您需要使用重载来创建属性,该重载采用您要创建的属性的前缀和命名空间URL,如下所示:

public class StackOverflow_14128649
{
    public static void Test()
    {
        string myInputXmlString = @"<ApplicationData>
                                        <something>else</something>
                                    </ApplicationData>";
        var doc = new XmlDocument();
        doc.LoadXml(myInputXmlString);

        XmlAttribute newAttr = doc.CreateAttribute(
            "xsi", 
            "noNamespaceSchemaLocation", 
            "http://www.w3.org/2001/XMLSchema-instance");
        newAttr.Value = "FullModeDataset.xsd";
        doc.DocumentElement.Attributes.Append(newAttr);

        var ms = new MemoryStream();
        XmlWriterSettings ws = new XmlWriterSettings
        {
            OmitXmlDeclaration = false,
            ConformanceLevel = ConformanceLevel.Document,
            Encoding = UTF8Encoding.UTF8
        };
        var tx = XmlWriter.Create(ms, ws);
        doc.Save(tx);
        tx.Flush();

        var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());
        Console.WriteLine(xmlString);
    }
}