我有一个XDocument,它是从一个字节数组(通过tcp/ip接收)创建的。
然后,我搜索特定的xml节点(XElements),并在检索到值“pop”后通过调用XElement.Remove()来弹出它。完成所有解析后,我想能够记录我没有解析的xml(XDocument中的剩余xml)。问题在于,当调用XElement.Remove()时,会保留额外的空格。我想知道最好的方法是去除这些额外的空格,同时保留剩余xml中的格式。
示例/样本代码
如果我通过套接字收到以下xml:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
</catalog>
我使用以下代码来解析这个xml并删除一些XElement:
private void socket_messageReceived(object sender, MessageReceivedEventArgs e)
{
XDocument xDoc;
try
{
using (MemoryStream xmlStream = new MemoryStream(e.XmlAsBytes))
using (XmlTextReader reader = new XmlTextReader(xmlStream))
{
xDoc = XDocument.Load(reader);
}
XElement Author = xDoc.Root.Descendants("author").FirstOrDefault();
XElement Title = xDoc.Root.Descendants("title").FirstOrDefault();
XElement Genre = xDoc.Root.Descendants("genre").FirstOrDefault();
// Do something with Author, Title, and Genre here...
if (Author != null) Author.Remove();
if (Title != null) Title.Remove();
if (Genre != null) Genre.Remove();
LogUnparsedXML(xDoc.ToString());
}
catch (Exception ex)
{
// Exception Handling here...
}
}
那么发送到LogUnparsedXML消息的xml的结果字符串将是:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
</catalog>
在这个人为的例子中,它似乎不是很重要,但在我的实际应用程序中,剩余的XML看起来相当混乱。我尝试使用XDocument.ToString重载方法,并传入SaveOptions枚举,但没有成功。我还尝试调用xDoc.Save方法并使用SaveOptions枚举保存到文件中。我尝试过使用几个不同的LINQ查询,这些查询使用XElement.Nodes().OfType<XText>()来尝试删除空格,但通常会把我想保留的空格和我试图去除的空格一起删除。感谢提前提供的帮助。Joe