Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

c# - How to print <?xml version="1.0"?> using XDocument

Is there any way to have an XDocument print the xml version when using the ToString method? Have it output something like this:

<?xml version="1.0"?>
<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...

I have the following:

var xdoc = new XDocument(new XDocumentType("Response", null, null, "
"), ...

which will print this which is fine, but it is missing the "<?xml version" as stated above.

<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...

I know that you can do this by outputting it manually my self. Just wanted to know if it was possible by using XDocument.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By using XDeclaration. This will add the declaration.

But with ToString() you will not get the desired output.

You need to use XDocument.Save() with one of his methods.

Full sample:

var doc = new XDocument(
        new XDeclaration("1.0", "utf-16", "yes"), 
        new XElement("blah", "blih"));

var wr = new StringWriter();
doc.Save(wr);
Console.Write(wr.ToString());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...