gpt4 book ai didi

c# - 向 MemoryStream XML 添加新属性

转载 作者:太空宇宙 更新时间:2023-11-03 20:20:07 27 4
gpt4 key购买 nike

我要补充

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

最佳答案

您需要使用重载来创建属性,该重载采用您要创建的属性的前缀和命名空间 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);
}
}

关于c# - 向 MemoryStream XML 添加新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14128649/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com