当前位置: 首页 > 编程语言 > C#

我的XDeclaration在哪里?Share

时间:2023-04-10 19:49:56 C#

我的XDeclaration在哪里?由于某种原因,以下代码生成不包含声明的XML:XDocumentxDocument=newXDocument(newXDeclaration("1.0","utf-8","yes"),newXElement("project",newXAttribute("number",project.ProjectNumber),newXElement("store",newXAttribute("number",project.StoreNumber)),//用户元素newXElement("user",newXAttribute("owner-id",project.OwnerID??0),newXElement("email",newXCData(project.OwnerEmail??"")),newXElement("project-name",newXCData(project.ProjectName??""))),//嵌套项目元素newXElement("nested-project",newXAttribute("version",newVersion(1,0)),newXElement("project",newXAttribute("version",newVersion(1,0))),xProjectItems=newXElement("project-items")),newXElement("每件价格",project.PricePerPart),newXElement("sheet-quantity",project.SheetQuantity),newXElement("edge-length",project.EdgeLength),newXElement("price",project.Price),newXElement("status",项目t.Status),xMaterialItems=newXElement("alternative-material-items"),xProductItems=newXElement("project-product-items"))));字符串strXML=xDocument.ToString();它是在我遗漏一些明显的东西之前发表的吗?谢谢。当您使用其中一种XDocument.Save方法时,XDeclaration将可用。例如:vardoc=newXDocument(newXDeclaration("1.0","utf-8","yes"),newXElement("test","data"));stringpath=Path.Combine(Path.GetTempPath(),"temp.xml");文档.保存(路径);Console.WriteLine(文件.ReadAllText(路径));或者你可以使用这个方法:varsw=newStringWriter();文档.保存(sw);字符串结果=sw.GetStringBuilder().ToString();控制台.WriteLine(结果);编辑:请注意,某些方法将utf-8规范转换为utf-16。如果你想强制它为utf-8,你将不得不使用这种不同的方法:using(varmem=newMemoryStream())writer.Formatting=Formatting.Indented;doc.WriteTo(作家);writer.Flush();mem.Flush();mem.Seek(0,SeekOrigin.Begin);使用(varreader=newStreamReader(mem)){varxml=reader.ReadToEnd();控制台.WriteLine(xml);文档没有明确说明xDocument.ToString()将输出XML声明,它只说:“返回该节点的缩进XML。”。在我的测试中,我发现以下方法将输出声明:在Declaration属性上使用ToString:stringstrXML=string.Concat(xDocument.Declaration.ToString(),"rn",xDocument.ToString());或者使用保存方法:stringstrXml;使用(varms=newMemoryStream()){xDocument.Save(ms);ms.Position=0;使用(varsr=newStreamReader(ms)){strXml=sr.ReadToEnd();我的回答(灵感来自@rsbarro的回答):stringxml=xDocument.Declaration.ToString()+xDocument.ToString();-或-stringxml=xDocument.Declaration.ToString()+xDocument.ToString(SaveOptions.DisableFormatting);至于为什么我认为在这种情况下使用+运算符是合适的,请参阅问题WhatisthebestwaytoconcatenatestringsusingC#?的答案。.以上就是C#学习教程:我的XDeclaration在哪里?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: