将xsd文件值添加到XmlAttribute

时间:2013-01-02 21:59:19

标签: c# xml

我如何用下面的代码创建一个正确xml的xml字符串..

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");
        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);

如何将xsd信息添加到此处,以便xml看起来像这样(包含“FullModeDataset.xsd”?

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

而不是当前代码输出的

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

1 个答案:

答案 0 :(得分:1)

这是否有效?

doc.DocumentElement.SetAttribute("noNamespaceSchemaLocation", 
        "http://www.w3.org/2001/XMLSchema-instance",
        "FullModeDataset.xsd");