XDocument.ToString ()이 XML 인코딩 태그를 삭제합니다.
toString () 함수에서 xml 인코딩을 얻는 방법이 있습니까?
예 :
xml.Save("myfile.xml");
~으로 이끌다
<?xml version="1.0" encoding="utf-8"?>
<Cooperations>
<Cooperation>
<CooperationId>xxx</CooperationId>
<CooperationName>Allianz Konzern</CooperationName>
<LogicalCustomers>
그러나
tb_output.Text = xml.toString();
다음과 같은 출력으로 이어집니다.
<Cooperations>
<Cooperation>
<CooperationId>xxx</CooperationId>
<CooperationName>Allianz Konzern</CooperationName>
<LogicalCustomers>
...
선언을 명시 적으로 작성하거나 StringWriter
및 호출을 사용 하십시오 Save()
.
using System;
using System.IO;
using System.Text;
using System.Xml.Linq;
class Test
{
static void Main()
{
string xml = @"<?xml version='1.0' encoding='utf-8'?>
<Cooperations>
<Cooperation />
</Cooperations>";
XDocument doc = XDocument.Parse(xml);
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
doc.Save(writer);
}
Console.WriteLine(builder);
}
}
확장 방법으로 쉽게 추가 할 수 있습니다.
public static string ToStringWithDeclaration(this XDocument doc)
{
if (doc == null)
{
throw new ArgumentNullException("doc");
}
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
doc.Save(writer);
}
return builder.ToString();
}
이것은 선언 이 없으면 충돌하지 않는다는 장점이 있습니다. :)
그런 다음 다음을 사용할 수 있습니다.
string x = doc.ToStringWithDeclaration();
.NET의 암시 적 인코딩이기 때문에 utf-16을 인코딩으로 사용 StringWriter
합니다. StringWriter
예 를 들어 항상 UTF-8을 사용 하는 것과 같이의 하위 클래스를 생성하여 직접 영향을 미칠 수 있습니다 .
선언 속성에는 XML 선언이 포함됩니다. 내용과 선언을 얻으려면 다음을 수행하십시오.
tb_output.Text = xml.Declaration.ToString() + xml.ToString()
이것을 사용하십시오 :
output.Text = String.Concat(xml.Declaration.ToString() , xml.ToString())
나는 소유했다
string distributorInfo = string.Empty;
XDocument distributors = new XDocument();
//below is important else distributors.Declaration.ToString() throws null exception
distributors.Declaration = new XDeclaration("1.0", "utf-8", "yes");
XElement rootElement = new XElement("Distributors");
XElement distributor = null;
XAttribute id = null;
distributor = new XElement("Distributor");
id = new XAttribute("Id", "12345678");
distributor.Add(id);
rootElement.Add(distributor);
distributor = new XElement("Distributor");
id = new XAttribute("Id", "22222222");
distributor.Add(id);
rootElement.Add(distributor);
distributors.Add(rootElement);
distributorInfo = String.Concat(distributors.Declaration.ToString(), distributors.ToString());
배포자 정보를 보려면 아래를 참조하십시오.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Distributors>
<Distributor Id="12345678" />
<Distributor Id="22222222" />
<Distributor Id="11111111" />
</Distributors>
다른 +1 답변과 비슷하지만 선언에 대해 조금 더 자세히 설명하고 약간 더 정확한 연결을 제공합니다.
<xml />
선언은 형식이 지정된 XML의 자체 줄에 있어야하므로 새 줄이 추가되었는지 확인합니다. 참고 : 사용 Environment.Newline
하면 플랫폼 별 개행이 생성됩니다.
// Parse xml declaration menthod
XDocument document1 =
XDocument.Parse(@"<?xml version=""1.0"" encoding=""iso-8859-1""?><rss version=""2.0""></rss>");
string result1 =
document1.Declaration.ToString() +
Environment.NewLine +
document1.ToString() ;
// Declare xml declaration method
XDocument document2 =
XDocument.Parse(@"<rss version=""2.0""></rss>");
document2.Declaration =
new XDeclaration("1.0", "iso-8859-1", null);
string result2 =
document2.Declaration.ToString() +
Environment.NewLine +
document2.ToString() ;
두 결과 모두 다음을 생성합니다.
<?xml version="1.0" encoding="iso-8859-1"?>
<rss version="2.0"></rss>
XmlWriter를 사용하고
Writer.WriteDocType()
방법.
이 답변 중 몇 가지는 포스터의 요청을 해결하지만 지나치게 복잡해 보입니다. 다음은 별도의 작성기가 필요하지 않고 누락 된 선언을 처리하며 표준 ToString SaveOptions 매개 변수를 지원하는 간단한 확장 메서드입니다.
public static string ToXmlString(this XDocument xdoc, SaveOptions options = SaveOptions.None)
{
var newLine = (options & SaveOptions.DisableFormatting) == SaveOptions.DisableFormatting ? "" : Environment.NewLine;
return xdoc.Declaration == null ? xdoc.ToString(options) : xdoc.Declaration + newLine + xdoc.ToString(options);
}
다만 교체, 확장을 사용 xml.ToString()
하여xml.ToXmlString()
string uploadCode = "UploadCode";
string LabName = "LabName";
XElement root = new XElement("TestLabs");
foreach (var item in returnList)
{
root.Add(new XElement("TestLab",
new XElement(uploadCode, item.UploadCode),
new XElement(LabName, item.LabName)
)
);
}
XDocument returnXML = new XDocument(new XDeclaration("1.0", "UTF-8","yes"),
root);
string returnVal;
using (var sw = new MemoryStream())
{
using (var strw = new StreamWriter(sw, System.Text.UTF8Encoding.UTF8))
{
returnXML.Save(strw);
returnVal = System.Text.UTF8Encoding.UTF8.GetString(sw.ToArray());
}
}
// ReturnVal has the string with XML data with XML declaration tag
참고 URL : https://stackoverflow.com/questions/1228976/xdocument-tostring-drops-xml-encoding-tag
'IT' 카테고리의 다른 글
“: nothing”옵션은 더 이상 사용하지 않을 것입니다. (0) | 2020.08.19 |
---|---|
편집하고 계속하기 : "다음 경우에는 변경이 허용되지 않습니다." (0) | 2020.08.19 |
튜플을 푸는 기술적 인 방법은 무엇입니까? (0) | 2020.08.19 |
react-router를 사용하여 브라우저에서 / # /을 중지하는 방법은 무엇입니까? (0) | 2020.08.19 |
TFS로 오프라인으로 작업하는 방법 (0) | 2020.08.19 |