如何使用C#读取文本文件中的xml并将其附加到richtextbox [英] How to read the xml in a text file and append it to richtextbox using C#

查看:209
本文介绍了如何使用C#读取文本文件中的xml并将其附加到richtextbox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文本文件中有xml

I have the xml in a text file is

<?xml version="1.0" encoding="utf-8" ?> 
- <TXT>
  <text font="Microsoft Sans Serif" color="#FF8000" font-size="16">testing</text> 
  <text font="Kal-72" color="#FFFF00" font-size="26">sample</text> 
  <text font="Arial Black" color="#8080FF" font-size="26">text</text> 
  </TXT>



我想将text标记的内容附加到richtextbox.即,文本标签元素字符串"testing sample text"将以其在文本标签中的相应字体类型,大小和颜色属性附加到richtextbox..



I would like to append the content of the text tag to the richtextbox. i.e., the text tag element string "testing sample text" is to be append to the richtextbox with their corresponding font type,size and color properties in text tag..

推荐答案

您可以使用LINQ to XML(最好)或XmlDocument类(需要更多代码)来从XML中获取价值.

此处 [
You can use LINQ to XML ( which is best ) or the XmlDocument class ( which requires more code ) to get the value out of your XML.

Here[^]

My guess:

IEnumerable<string> text =
    from item in doc.Descendants("text")
    select (string) item.Attribute("PartNumber");



我不确定是否需要引用顶级元素.当然,您需要先用文件加载XDocument.



I am not sure if you need to reference the top level element or not. Of course you need to load the XDocument with your file first.


首先将文本转换为xml文件并执行以下代码

First convert the text to xml file and do the following code

 var textConfiguration = XDocument.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.xml")); 
if (textConfiguration != null) 
{ 
textConfiguration.Descendants("Configuration").Descendants("text").ToList().ForEach(text => 
{ 
font = text.Attribute("font").Value; 
color = text.Attribute("color").Value; 
fontsize = text.Attribute("font-size").Value; 
textToAppend = text.Value; 
richTextBox1.SelectionColor = Color.FromName(color); 
richTextBox1.SelectionFont = new Font(font, int.Parse(fontsize), FontStyle.Regular); 
richTextBox1.AppendText(textToAppend); 
}); 
} 


这篇关于如何使用C#读取文本文件中的xml并将其附加到richtextbox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆