2

XDocumentXML プロローグ (" <?xml version="1.0" encoding="UTF-8"?>" など) を大文字で出力したい。

これが私が現在行っている方法ですが、うまくいかないようです:

XDocument doc = new XDocument
(
     new XDeclaration("1.0", "UTF-8",""),
     bla bla bla);
     doc.Save(@"Z:\test.xml");
)

このコードは機能していません。小文字で出てきます。これを行っている間、ident とフォーマットは変更されるべきではありません。どんな助けでも大歓迎です。ありがとう。

*編集: *この質問は未解決です。これを解決するためのアイデアは他にありますか。

4

4 に答える 4

2
XDocument xdoc = new XDocument();

.... // do your stuff here

string finalDoc = xdoc.ToString();
string header = finalDoc.Substring(0,finalDoc.IndexOf("?>") + 2); // end of header tag

finalDoc = finalDoc.Replace(header, header.ToUpper());  // replace header with the uppercase version

.... // do stuff with the xml with the upper case header

編集:

ああ、UTF-8 の大文字だけが必要ですか?

次に、これはより正しいです:

XDocument xdoc = new XDocument();

.... // do your stuff here

string finalDoc = xdoc.ToString();
string header = finalDoc.Substring(0,finalDoc.IndexOf("?>") + 2); // end of header tag
string encoding = header.Substring(header.IndexOf("encoding=") + 10);
encoding = encoding.Substring(0,encoding.IndexOf("\""); // only get encoding content

// replace encoding with the uppercase version in header, then replace old header with new one.
finalDoc = finalDoc.Replace(header, header.Replace(encoding, encoding.ToUpper()));

.... // do stuff with the xml with the upper case header

これは、エンコーディングにあるものを手動で大文字に置き換えるだけです。

于 2013-05-24T04:10:30.883 に答える
0

XmlTextWriterを使用したサンプル ソリューションを次に示します。

もっと最適な方法があるはずだと確信しています..

            XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8","d"));
            doc.Add(new XElement("MyRoot", "Value blah"));


            using (var str = new StringWriter())
            using (var xmlTextWriter = new XmlTextWriter(str))
            {
                xmlTextWriter.Formatting = Formatting.Indented;
                xmlTextWriter.Indentation = 4;

                xmlTextWriter.WriteRaw(doc.Declaration.ToString().ToUpper());

                foreach (var xElement in doc.Elements())
                {
                   xmlTextWriter.WriteElementString(xElement.Name.ToString(), xElement.Value);
                }

                var finalOutput = str.ToString();
            }

FinalOutputには以下が含まれます。

<?XML VERSION="1.0" ENCODING="UTF-8" STANDALONE="D"?>
<MyRoot>Value blah</MyRoot>
于 2013-05-24T04:17:20.350 に答える