解决使用XDocument操作FlowDocument时XML被格式化的问题

最近需要对WPF中的FlowDocument进行解析编辑操作,理想的办法是解析成FlowDocument对象,但是有些操作不是很方便。

 

FlowDocument实际上还是XML,我直接使用XDocument去进行解析操作更方便。

如下就是一个FlowDocument的一个段落

1 <Section xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xml:space="preserve" TextAlignment="Left" LineHeight="Auto" IsHyphenationEnabled="False" xml:lang="en-us" FlowDirection="LeftToRight" ><Paragraph TextAlignment="Justify" NumberSubstitution.CultureSource="Text" Foreground="#FF000000"><Run>这是一个段落</Run></Paragraph></Section>

 

使用如下的代码添加一个属性后

1  var sr= new StringReader(“xxxxxxxxFlowDocument”);
2  var doc = XDocument.Load(sr);
3  foreach (XElement paragraph in doc.Root.Elements())
4  {
5      paragraph.Add(new XAttribute("Att", $"AttValue"));
6  }
7  sr.Dispose();
8  var flowDocument =  doc.ToString();

 

XML会被格式化,在XML里,这种格式化显示是不会有问题的,因为只解析节点。

FlowDocument与XML不同的是,节点之间的空格/空行会被解析成内容,造成格式显示错误

 

1 <Section xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xml:space="preserve" TextAlignment="Left" LineHeight="Auto" IsHyphenationEnabled="False" xml:lang="en-us">
2   <Paragraph TextAlignment="Justify" NumberSubstitution.CultureSource="Text" Foreground="#FF000000" Att="AttValue">
3     <Run>这是一个段落</Run>
4   </Paragraph>
5 </Section>

 

解决办法如下:

1 var flowDocument =  doc.ToString(SaveOptions.DisableFormatting);

 

这样元素还是保持原来的格式

posted @ 2024-05-29 11:57  zhaotianff  阅读(9)  评论(0编辑  收藏  举报