誰かが私にこの振る舞いを説明できますか?
投稿の下部にあるスニペットを最初の文字列で実行すると、入力に使用されたものとまったく同じ文字列が返されます。それが私が期待したことです。
入力 1:
<?xml version='1.0' encoding='UTF-8'?>
<Company>
<Creator>Me</Creator>
<CreationDateTime>2010-01-25T21:58:32.493</CreationDateTime>
<Contacts>
<Contact>
<ContactID>365</ContactID>
</Contact>
</Contacts>
</Company>
出力 1:
<?xml version='1.0' encoding='UTF-8'?>
<Company>
<Creator>Me</Creator>
<CreationDateTime>2010-01-25T21:58:32.493</CreationDateTime>
<Contacts>
<Contact>
<ContactID>365</ContactID>
</Contact>
</Contacts>
</Company>
2 行目 ( const string xml
) を使用すると、まったく同じ文字列ですが、2 行ではなく 1 行で次のように返されます。
入力 2
<?xml version='1.0' encoding='UTF-8'?>
<Company>
<Creator>Me</Creator>
<CreationDateTime>2010-01-25T21:58:32.493</CreationDateTime>
<Contacts>
<Contact>
<ContactID>365</ContactID>
</Contact>
</Contacts>
</Company>
出力 2
<?xml version='1.0' encoding='UTF-8'?>
<Creator>Me</Creator>2010-01-25T21:58:32.493
<Contacts>
<Contact>
<ContactID>365</ContactID>
</Contact>
</Contacts>
2 つの唯一の違いは、最初の出力では xml 宣言の直後に改行があることですが、ご覧のとおり、2 番目の出力では Parent タグと 3 番目のタグが欠落しています。何か考えはありますか?
使用したコードは次のとおりです。
public void XmlReader_Eats_Tags_IsTrue()
{
//this first xml declaration is on two lines - line break is right after the xml declaration (I am not sure how to add the line break using the markdown, so if you execute the code on your machine, please add it)
const string xml = @"<?xml version='1.0' encoding='UTF-8'?><Company><Creator>Me</Creator><CreationDateTime>2010-01-25T21:58:32.493</CreationDateTime><Contacts><Contact><ContactID>365</ContactID></Contact></Contacts></Company>";
//The seconde xml declaration is on one line
//const string xml = @"<?xml version='1.0' encoding='UTF-8'?><Company><Creator>Me</Creator><CreationDateTime>2010-01-25T21:58:32.493</CreationDateTime><Contacts><Contact><ContactID>365</ContactID></Contact></Contacts></Company>";
BufferedStream stream = new BufferedStream(new MemoryStream());
stream.Write(Encoding.ASCII.GetBytes(xml), 0, xml.Length);
stream.Seek(0, SeekOrigin.Begin);
StreamReader streamReaderXml = new StreamReader(stream);
XmlReader xmlR = XmlReader.Create(streamReaderXml);
XmlReaderSettings xmlReaderset =
new XmlReaderSettings{ValidationType = ValidationType.Schema};
xmlReaderset.Schemas.ValidationEventHandler += ValidationCallBack;
MemoryStream ms = new MemoryStream();
XmlWriterSettings xmlWriterSettings =
new XmlWriterSettings{
Encoding = new UTF8Encoding(false),
ConformanceLevel = ConformanceLevel.Fragment
};
using (XmlWriter xmlTw = XmlWriter.Create(ms, xmlWriterSettings))
{
using (XmlReader xmlRead = XmlReader.Create(xmlR, xmlReaderset))
{
int i = 0;
while (xmlRead.Read())
{
Console.WriteLine("{0}:{1}; node type: {2}", i, xmlRead.Name, xmlRead.NodeType);
// Reads the whole file and will call the validation handler subroutine if an error is detected.
xmlTw.WriteNode(xmlRead, true);
i++;
}
xmlTw.Flush();
xmlRead.Close();
}
string xmlString = Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine(xmlString);
}
}