1

我想添加

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 字符串中?

4

1 回答 1

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);
    }
}
于 2013-01-02T20:34:45.500 回答