我该如何更改” &quot到' '在xmldocument c#中?

发布于 2025-02-13 09:44:09 字数 655 浏览 1 评论 0 原文

当前,我有一个代码项目,可以将数据从Excel转换为XML,并且我正在使用XMLDOCUMEMENT将XML文件写入可用软件中的testcase。但是在运行XML时,它只会收到。

<?xml版本='1.0'encoding ='utf -8'?>

当我使用xmldocument的createxmldeclaration函数时,

XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("'1.0", "'utf-8'", null);

我的结果 - > <?xml版本=“ 1.0” encoding =“ utf-8”?>

我尝试修改它<?xml版本=“'1.0''1.0'condoding =“'utf-- 8'?> ,我得到了例外:

在 system.xml.dll错误的XML版本信息。 XML必须匹配 生产“版本” :: ='1.' [0-9]+“。

我如何在createxmldeclaration中使用''或将另一个API用作Xmldocument的替代方案?

Currently, I have a code project to convert data from excel to xml and I am using XmlDocument to write xml file to run testcase in available software. But in that software when running xml it only receives.

<?xml version='1.0' encoding='utf-8'?>

When I use CreateXmlDeclaration function of XmlDocument

XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("'1.0", "'utf-8'", null);

My result -> <?xml version="1.0" encoding="utf-8"?>

I try modify it <?xml version="'1.0'" encoding="'utf-8'"?> and I get exception:

an unhandled exception of type 'System.ArgumentException' occurred in
System.Xml.dll Wrong XML version information. The XML must match
production "VersionNum ::= '1.' [0-9]+".

How can I use ' ' in CreateXmlDeclaration or use another API as an alternative to XmlDocument ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痴意少年 2025-02-20 09:44:11

您在这里有几个问题:

  1. 无需手动将XML声明添加到 xmldocument 通过调用 creationexmldeclaration(creationexmldeclaration() 。当您调用 xmldocument.save() 。当您检查代码> outerxml 或调用 xmldocument.writocument.writeTo(writocument.writeto() a>。


  2. 写XML时使用 您可以通过设置 [1]

    请注意,此属性同时控制了XML声明中使用的报价字符,也控制了用于属性值的报价字符。

    还请注意, XMLTEXTWRITER 已被弃用而不是致电 xmlwriter.create() ,似乎没有一种使用 xmlWriterSettings

因此,如果您想对XML声明和属性值都使用单个报价字符,则可以介绍以下扩展方法:

public static partial class XmlSerializationHelper
{
    public static string GetOuterXml(this XmlDocument doc, bool indent = true, char quoteChar = '"')
    {
        if (doc == null)
            return null;
        using (var textWriter = new StringWriterWithEncoding())
        {
            using (var xmlWriter = new XmlTextWriter(textWriter) { Formatting = indent ? Formatting.Indented : Formatting.None, QuoteChar = quoteChar })
            {
                doc.Save(xmlWriter);
            }
            return textWriter.ToString();
        }
    }
}

public sealed class StringWriterWithEncoding : StringWriter
{
    // From this answer https://stackoverflow.com/a/42584394/3744182
    // To https://stackoverflow.com/questions/42583299/xmlwriter-encoding-utf-8-using-stringwriter-in-c-sharp
    public StringWriterWithEncoding() : this(Encoding.UTF8) { }
    public StringWriterWithEncoding(Encoding encoding) => this.Encoding = encoding;
    public override Encoding Encoding { get; }
}

,对于xml &lt; foo name =“ Hello”&gt; bar ID =“ 101”&gt; var value&lt;/bar&gt;&lt;/foo&gt; ,方法
doc.getOuterxml(quodechar:'\'')将生成:

<?xml version='1.0' encoding='utf-8'?>
<foo Name='hello'>
  <bar Id='101'>var value</bar>
</foo>

demo fiddle#1 在这里a>。

请注意,单引号字符均用于XML声明和属性值。您的问题尚不清楚,但是如果您需要XML声明和双引号,否则您将需要子类 xmltextwriter so:

public static partial class XmlSerializationHelper
{
    public static string GetOuterXml(this XmlDocument doc, bool indent = true)
    {
        if (doc == null)
            return null;
        using (var textWriter = new StringWriterWithEncoding())
        {
            using (var xmlWriter = new CustomQuoteCharXmlTextWriter(textWriter) { Formatting = indent ? Formatting.Indented : Formatting.None })
            {
                doc.Save(xmlWriter);
            }
            return textWriter.ToString();
        }
    }
}

public class CustomQuoteCharXmlTextWriter : XmlTextWriter
{
    public CustomQuoteCharXmlTextWriter(Stream w, Encoding encoding) : base(w, encoding) => QuoteChar = '\'';
    public CustomQuoteCharXmlTextWriter(String filename, Encoding encoding) : base(filename, encoding) => QuoteChar = '\'';
    public CustomQuoteCharXmlTextWriter(TextWriter w) : base(w) => QuoteChar = '\'';
    
    public override void WriteStartDocument() 
    {
        base.WriteStartDocument();
        QuoteChar = '"';
    }
}

现在现在 doc.getouterxml()将返回:

<?xml version='1.0' encoding='utf-8'?>
<foo Name="hello">
  <bar Id="101">var value</bar>
</foo>

演示小提琴#2 在这里


[1] 请参阅这个答案 by Peter Ritchie to 一个可以强制XMLWriter以单引号写元素?

You have a couple of issues here:

  1. There is no need to manually add an XML Declaration to an XmlDocument by calling CreateXmlDeclaration(). The XML Declaration will be written automatically using the current encoding when you call one of the overloads of XmlDocument.Save(). It will not be written when you inspect the value of OuterXml or call XmlDocument.WriteTo().

  2. When writing XML using XmlTextWriter you may control the quote character by setting XmlTextWriter.QuoteChar = '\''[1].

    Note that this property controls both the quote character used in the XML declaration, and the quote character used for attribute values.

    Note also that, while XmlTextWriter has been deprecated in favor of calling XmlWriter.Create(), there does not appear to be a way to set the quote character using XmlWriterSettings.

Thus, if you want to use a single quote character for both the XML declaration and attribute values, you can introduce the following extension method:

public static partial class XmlSerializationHelper
{
    public static string GetOuterXml(this XmlDocument doc, bool indent = true, char quoteChar = '"')
    {
        if (doc == null)
            return null;
        using (var textWriter = new StringWriterWithEncoding())
        {
            using (var xmlWriter = new XmlTextWriter(textWriter) { Formatting = indent ? Formatting.Indented : Formatting.None, QuoteChar = quoteChar })
            {
                doc.Save(xmlWriter);
            }
            return textWriter.ToString();
        }
    }
}

public sealed class StringWriterWithEncoding : StringWriter
{
    // From this answer https://stackoverflow.com/a/42584394/3744182
    // To https://stackoverflow.com/questions/42583299/xmlwriter-encoding-utf-8-using-stringwriter-in-c-sharp
    public StringWriterWithEncoding() : this(Encoding.UTF8) { }
    public StringWriterWithEncoding(Encoding encoding) => this.Encoding = encoding;
    public override Encoding Encoding { get; }
}

And, for the XML <foo Name="hello"><bar Id="101">var value</bar></foo>, the method
doc.GetOuterXml(quoteChar : '\'') will generate:

<?xml version='1.0' encoding='utf-8'?>
<foo Name='hello'>
  <bar Id='101'>var value</bar>
</foo>

Demo fiddle #1 here.

Notice that the single quote character is used for both the XML declaration and attribute values. Your question is unclear, but if you need a single quote for the XML Declaration only and double quotes otherwise, you will need to subclass XmlTextWriter like so:

public static partial class XmlSerializationHelper
{
    public static string GetOuterXml(this XmlDocument doc, bool indent = true)
    {
        if (doc == null)
            return null;
        using (var textWriter = new StringWriterWithEncoding())
        {
            using (var xmlWriter = new CustomQuoteCharXmlTextWriter(textWriter) { Formatting = indent ? Formatting.Indented : Formatting.None })
            {
                doc.Save(xmlWriter);
            }
            return textWriter.ToString();
        }
    }
}

public class CustomQuoteCharXmlTextWriter : XmlTextWriter
{
    public CustomQuoteCharXmlTextWriter(Stream w, Encoding encoding) : base(w, encoding) => QuoteChar = '\'';
    public CustomQuoteCharXmlTextWriter(String filename, Encoding encoding) : base(filename, encoding) => QuoteChar = '\'';
    public CustomQuoteCharXmlTextWriter(TextWriter w) : base(w) => QuoteChar = '\'';
    
    public override void WriteStartDocument() 
    {
        base.WriteStartDocument();
        QuoteChar = '"';
    }
}

And now doc.GetOuterXml() will return:

<?xml version='1.0' encoding='utf-8'?>
<foo Name="hello">
  <bar Id="101">var value</bar>
</foo>

Demo fiddle #2 here.


[1] See this answer by Peter Ritchie to Can one force XMLWriter to write elements in single quotes?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文