简体   繁体   English

从xml文件中删除独立属性

[英]Remove standalone attribute from xml file

I have an xml file which I need to modify and write it back to an outputfile. 我有一个xml文件,我需要对其进行修改并将其写回到输出文件中。 The problem is that the result outputfile contains an extra attribute 'standalone' in the root declartion which does not exist in the original inputfile. 问题在于结果输出文件在根声明中包含一个额外的属性“独立”,该属性在原始输入文件中不存在。 Is there any way how I can prevent from XmlDocument adding this attribute ? 有什么办法可以防止XmlDocument添加此属性?

The code I have tried: 我尝试过的代码:

//read input xml
 XmlDocument xDoc  = new XmlDocument();
 xDoc.Load(originalFile);

//do some stuff
//....

//write back to output
using(XmlTextWriter xml2 = new XmlTextWriter(outputFile, Encoding.UTF8) { Formatting = Formatting.Indented })
            {   
                xDoc.CreateXmlDeclaration("1.0", null, "");
                xDoc.Save(xml2);

            }

inputfile contains this: 输入文件包含以下内容:

<?xml version="1.0" encoding="UTF-8" ?>
...

output.xml contains this: output.xml包含以下内容:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
...

The standalone parameter should be null or String.empty . 独立参数应为nullString.empty

xDoc.CreateXmlDeclaration("1.0", null, null);

Also CreateXmlDecleration just creates a declaration object. 同样, CreateXmlDecleration只会创建一个声明对象。 You still need to add it to the document, like this: 您仍然需要将其添加到文档中,如下所示:

XmlDeclaration xDecl = xDoc.CreateXmlDeclaration("1.0", null, null);
if (xDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
  xDoc.ReplaceChild(xDecl, xDoc.FirstChild);
else
  xDoc.InsertBefore(xDecl, xDoc.DocumentElement);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM