我有如下XML文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<sami>
<title>IN[1]=false</title>
<title>IN[2]=true</title>
<title>OUT[1]=true</title>
<title>OUT[2]=flase</title>
<title>OUT[3]=flase</title>
<title>OUT[4]=flase</title>
<title>$IN[5]=false</title>
</sami>
问题:如何使用C#每秒读取xml数据?
我尝试了以下操作:
private void Form1_Load(object sender, EventArgs e)
{
DateTime nextRead;
Thread thread = new Thread(() =>
{
nextRead = DateTime.Now.AddSeconds(1000);
XDocument doc = XDocument.Load("C:\\Users\\lenovo\\Desktop\\Sxml.xml");
var result = doc.Descendants("title").ToList();
textBox1.Text = result[0].Value;
// listBox1.Items.Add(result[0].Value);
// listBox1.Items.Add(result[1].Value);
// listBox1.Items.Add(result[2].Value);
Thread.Sleep(Math.Max(0, (DateTime.Now - nextRead).Milliseconds));
});
thread.Start();
}
答案 0 :(得分:1)
您可以使用Task.Delay重复读取xml文件。 1,创建一个任务方法以重复读取xml文件:
{
"name": "dragi",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"prop-types": "^15.6.2",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-redux": "^5.0.7",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-scripts": "1.1.5",
"redux": "^4.0.0",
"redux-devtools-extension": "^2.13.5",
"redux-thunk": "^2.3.0",
"semantic-ui-css": "^2.3.3",
"semantic-ui-react": "^0.82.3",
"validator": "^10.7.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"lint": "eslint src"
},
"devDependencies": {
"eslint": "^5.5.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-config-prettier": "^3.0.1",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.1",
"eslint-plugin-prettier": "^2.6.2",
"eslint-plugin-react": "^7.11.1",
"prettier": "^1.14.2"
},
"proxy": "http://localhost:8080"
}
并在需要重复阅读的地方调用它:
static async Task RepeadtReadingXml(int delayMillis, int repeatMillis, CancellationToken ct)
{
Console.WriteLine("{0}: Start reading xml file", DateTime.Now);
await Task.Delay(delayMillis, ct);
while (true)
{
Console.WriteLine("{0}: Reading xml file every 1 sec", DateTime.Now);
//***************************************************//
// Add you logic to read your xml file here //
//***************************************************//
await Task.Delay(repeatMillis, ct);
}
}
答案 1 :(得分:0)
为此,您需要从工具箱中添加到表单Timer
。
将timer1
间隔设置为1000毫秒。为timer1.Tick
事件创建事件hadnler:
public partial class Form1 : Form
{
XDocument doc;
public Form1()
{
InitializeComponent();
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
doc = XDocument.Load("C:\\Users\\Mi\\Desktop\\Sxml.xml");
var result = doc.Descendants("title").ToList();
textBox1.Text = result[0].Value;
listBox1.Items.Add(result[0].Value);
listBox1.Items.Add(result[1].Value);
listBox1.Items.Add(result[2].Value);
}
}