首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XmlDocument.Save()与XDocument.Save()

XmlDocument.Save()与XDocument.Save()
EN

Stack Overflow用户
提问于 2020-09-25 13:51:23
回答 1查看 364关注 0票数 1

我使用XmlDocument、XmlElement等进行了一些XML操作,我用XDocument、XElement等代码替换了它,以使其现代化。但是,元素的某些内部文本包含字符'\x4'。使用XmlDocument.Save()时,它被保存为,一切都很正常,即使使用第三方工具也是如此。但是XDocument.Save()抛出

代码语言:javascript
复制
System.ArgumentException: '', hexadecimal value 0x04, is an invalid character.
  + System.Xml.XmlUtf8RawTextWriter.InvalidXmlChar(int, System.Byte*, bool)
  + System.Xml.XmlUtf8RawTextWriter.WriteElementTextBlock(System.Char*, System.Char*)
  + System.Xml.XmlUtf8RawTextWriter.WriteString(string)
  + System.Xml.XmlUtf8RawTextWriterIndent.WriteString(string)
  + System.Xml.XmlWellFormedWriter.WriteString(string)
  + System.Xml.Linq.ElementWriter.WriteElement(System.Xml.Linq.XElement)
  + System.Xml.Linq.XElement.WriteTo(System.Xml.XmlWriter)
  + System.Xml.Linq.XContainer.WriteContentTo(System.Xml.XmlWriter)
  + System.Xml.Linq.XDocument.WriteTo(System.Xml.XmlWriter)
  + System.Xml.Linq.XDocument.Save(string, System.Xml.Linq.SaveOptions)
  + System.Xml.Linq.XDocument.Save(string)

暂时,我使用了XmlConvert.EncodeName(),但这会将其转换为_x0004_,除非用XmlConvert.DecodeName()解码,否则将不允许读取校正。

我能实现以前的保存功能吗?

最小步骤:

代码语言:javascript
复制
    //ok
    Console.WriteLine(new XDocument(new XElement("test","aa")).ToString());
    //System.ArgumentException: '', hexadecimal value 0x04, is an invalid character.
    Console.WriteLine(new XDocument(new XElement("test","aa \x4")).ToString());

小提琴

编辑:搜索.NET源代码,我发现以前正确的行为可能是由私有的XmlTextEncoder.WriteCharEntityImpl(字符串)完成的。然而,这个类似乎没有文档化,我无法想象如何利用它。

EN

回答 1

Stack Overflow用户

发布于 2020-09-26 10:45:50

我找到了一种可以接受的方式来做我想做的事情,通过使用一个XmlTextWriter来保存,所以我把它作为我自己问题的答案。但是,如果只有LINQ到XML类有解决方案的话,我更愿意这样做。

代码语言:javascript
复制
using System;
using System.Xml;
using System.Xml.Linq;
                    
public class Program
{
    public static void Main()
    {
         var xdoc=new XDocument(new XElement("Params", new XElement("test","aa1 \x4")));
         using (var xw = new XmlTextWriter(Console.Out)
                {
                    Formatting=Formatting.Indented
                } )
                    xdoc.WriteTo(xw);   
    }
}

小提琴

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64065477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档