Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何构建xml节并保存到文件(本身不是有效的xml文档)_C#_Xml - Fatal编程技术网

C# 如何构建xml节并保存到文件(本身不是有效的xml文档)

C# 如何构建xml节并保存到文件(本身不是有效的xml文档),c#,xml,C#,Xml,我试图构建XML文档的一小部分,并将其包含在最终文档中。 使用XDocument时,我遇到一个异常: “此操作将创建结构不正确的文档。” 因为我的片段有多个“根”节点 由于该文件将包含在一个较大的文档中,因此我的基本元素将不会出现在最终文档的根目录中 XDocument constsDocument = new XDocument( new XComment($" Consts section generated on {DateTime.Now} "), new XCommen

我试图构建XML文档的一小部分,并将其包含在最终文档中。 使用
XDocument
时,我遇到一个异常:

“此操作将创建结构不正确的文档。”

因为我的片段有多个“根”节点

由于该文件将包含在一个较大的文档中,因此我的基本元素将不会出现在最终文档的根目录中

XDocument constsDocument = new XDocument(
    new XComment($" Consts section generated on {DateTime.Now} "),
    new XComment($" First group of constants. "),
    FirstTextConsts(MyFirstCollection),
    new XComment($" Refrigerant constants. "),
    SecondTextConsts(MySecondCollection)
    );
// To avoid xml file starting with <?xml version="1.0" encoding="utf-8"?> use stringbuilder and StreamWriter.
StringBuilder sb = new StringBuilder();
XmlWriterSettings xws = new XmlWriterSettings
{
    OmitXmlDeclaration = true,
    Indent = true
};
using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
    constsDocument.Save(xw);
}
System.IO.StreamWriter file = new System.IO.StreamWriter(_outputFileName);
file.WriteLine(sb.ToString()); 
file.Close();
在写入文件之前,我剥离元素:

    file.WriteLine(sb.ToString().Replace("<root>" + Environment.NewLine, "").Replace(Environment.NewLine + "</root>", ""));
file.WriteLine(sb.ToString().Replace(“+Environment.NewLine,”).Replace(Environment.NewLine+”,”);

您可以声明希望XML只是一个片段,然后从XDocument切换到XMLDocument:

XmlDocument constDocument = new XmlDocument();
constDocument.CreateComment(" Consts section generated on {DateTime.Now} ");
constDocument.CreateComment(" First group of constants. ");
FirstTextConsts(MyFirstCollection); // Need to be adapted
constDocument.CreateComment(" Refrigerant constants. ");
SecondTextConsts(MySecondCollection); // Need to be adapted
XmlDocumentFragment fragDocument = constDocument.CreateDocumentFragment();
fragDocument.InnerXml = "<const>fragment</const><const>fragment2</const>"; // Need to be adapted

StringBuilder sb = new StringBuilder();
XmlWriterSettings xws = new XmlWriterSettings
{
    ConformanceLevel = ConformanceLevel.Fragment,
    OmitXmlDeclaration = true,
    Indent = true
};
using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
    fragDocument.WriteContentTo(xw);
}
System.IO.StreamWriter file = new System.IO.StreamWriter(_outputFileName);
file.WriteLine(sb.ToString()); 
file.Close();
XmlDocument constDocument=新的XmlDocument();
CreateComment(“在{DateTime.Now}上生成的Consts节”);
CreateComment(“第一组常量”);
FirstTextConsts(MyFirstCollection);//需要调整
constDocument.CreateComment(“制冷剂常量”);
SecondTextConsts(MySecondCollection);//需要调整
XmlDocumentFragment fragDocument=constDocument.CreateDocumentFragment();
fragDocument.InnerXml=“fragment2”//需要调整
StringBuilder sb=新的StringBuilder();
xws=新的XmlWriterSettings
{
ConformanceLevel=ConformanceLevel.Fragment,
OmitXmlDeclaration=true,
缩进=真
};
使用(xmlwriterxw=XmlWriter.Create(sb,xws))
{
fragDocument.writeContento(xw);
}
System.IO.StreamWriter file=新的System.IO.StreamWriter(_outputFileName);
file.WriteLine(sb.ToString());
file.Close();
或添加算术根元素:

    file.WriteLine(sb.ToString().Replace("<root>" + Environment.NewLine, "").Replace(Environment.NewLine + "</root>", ""));
"<aritificialroot>" + fragment + "</aritificialroot>"
“”+fragment+“”

无法创建无效的
XDocument
(由于有多个“根”节点)。因此,您需要创建一个节点列表,并将其写入文档片段

var constsDocument = new List<XNode> {
           new XComment($" Consts section generated on {DateTime.Now} "),
           new XComment($" First group of constants. "),
           new XElement("example"),
           new XComment($" Refrigerant constants. "),
           new XElement("another")
};
// To avoid xml file starting with <?xml version="1.0" encoding="utf-8"?> use stringbuilder and StreamWriter.
StringBuilder sb = new StringBuilder();
XmlWriterSettings xws = new XmlWriterSettings
{
    OmitXmlDeclaration = true,
    Indent = true,
    ConformanceLevel = ConformanceLevel.Fragment
};
using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
    foreach (var element in constsDocument)
    {
        element.WriteTo(xw);
    }
}
System.IO.StreamWriter file = new System.IO.StreamWriter(_outputPath);
file.WriteLine(sb.ToString());
file.Close();


我编辑了我的问题,以说明在文档创建过程中调用的两种方法。正如你所建议的那样,它们在对象初始值设定项中不起作用?@TheRoadrunner我刚刚用一个可能的解决方案更新了我的答案,以使用返回多个
XElement
实例的两个方法。非常感谢你的更新。它按照您建议的方式工作。我最终返回到XDocument并添加了一个虚假元素,然后在创建文件之前将其从stringbuilder中删除。原因是您的sugested解决方案只支持在第一层调用我的助手方法,而在现实生活中,我也在更深的层调用助手方法。
var constsDocument = new List<XNode> {
           new XComment($" Consts section generated on {DateTime.Now} "),
           new XComment($" First group of constants. "),
           new XElement("example"),
           new XComment($" Refrigerant constants. "),
           new XElement("another")
};
// To avoid xml file starting with <?xml version="1.0" encoding="utf-8"?> use stringbuilder and StreamWriter.
StringBuilder sb = new StringBuilder();
XmlWriterSettings xws = new XmlWriterSettings
{
    OmitXmlDeclaration = true,
    Indent = true,
    ConformanceLevel = ConformanceLevel.Fragment
};
using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
    foreach (var element in constsDocument)
    {
        element.WriteTo(xw);
    }
}
System.IO.StreamWriter file = new System.IO.StreamWriter(_outputPath);
file.WriteLine(sb.ToString());
file.Close();
var constsDocument = new List<IEnumerable<XNode>> {
    new [] { new XComment($" Consts section generated on {DateTime.Now} ") },
    new [] { new XComment($" First group of constants. ") },
    FirstTextConsts(MyFirstCollection),
    new [] { new XComment($" Refrigerant constants. ") },
    SecondTextConsts(MySecondCollection)
);
foreach (var element in constsDocument.SelectMany(n => n))