我目前正在使用Microsoft开发语音识别应用程序,输出应该是遵循某种结构的XML文件,例如:
<?xml version="1.0" encoding="UTF-8"?>
<Speech>
<Item Words="hello" Confidence="0,5705749" Semantic="Child" />
<Item Words="goodbye" Confidence="0,7705913" Semantic="Child" />
</Speech>
Item节点包含所有已读取的信息,这些信息被识别为Kinect的语音识别器。目标是:每次识别一个新单词时,都会添加一个新的<Item>
节点及其相应的属性。
我在更新过程中遇到了问题,即每次我添加一个新节点时,它都会覆盖最后一个节点,最后一个节点只剩下<Item>
节点。我在谷歌上搜索过,并试图应用其搜索结果中的解决方案,但没有成功。
写入XML文件的函数如下:
void WriteXML(string result, float confidence, string semantic, string typeOfSpeech)
{
try
{
//pick whatever filename with .xml extension
string filename = "XML" + "SpeechOutput" + ".xml";
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(filename);
}
catch (System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("Speech");
xmlWriter.Close();
xmlDoc.Load(filename);
}
XmlNode root = xmlDoc.DocumentElement;
XmlNode lastWord = root.LastChild;
XmlElement childNode = xmlDoc.CreateElement("Item");
childNode.SetAttribute("Words", result);
childNode.SetAttribute("Confidence", confidence.ToString());
childNode.SetAttribute("Semantic", semantic);
root.InsertAfter(childNode, lastWord);
xmlDoc.Save("W:\\" + filename);
}
catch (Exception ex)
{
WriteError(ex.ToString());
}
}
任何帮助都将不胜感激!
为了更容易地进行测试,我将将代码添加到一个简单的应用程序中,以测试此方法:
namespace XMLTesting
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private string typeOfSpeech;
public MainWindow()
{
InitializeComponent();
WriteXML("test", 1, "semantic", "typeofspeech");
WriteXML("test2", 2, "semantic", "typeofspeech");
}
void WriteXML(string result, float confidence, string semantic, string typeOfSpeech)
{
try
{
//pick whatever filename with .xml extension
string filename = "XML" + "SpeechOutput" + ".xml";
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(filename);
}
catch (System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("Speech");
xmlWriter.Close();
xmlDoc.Load(filename);
}
XmlNode root = xmlDoc.DocumentElement;
XmlNode lastWord = root.LastChild;
XmlElement childNode = xmlDoc.CreateElement("Item");
childNode.SetAttribute("Words", result);
childNode.SetAttribute("Confidence", confidence.ToString());
childNode.SetAttribute("Semantic", semantic);
root.InsertAfter(childNode, lastWord);
xmlDoc.Save("W:\\" + filename);
}
catch (Exception ex)
{
WriteError(ex.ToString());
}
}
void WriteError(string str)
{
//outputBox.Text = str;
}
}
}
此应用程序的输出文件是:
<?xml version="1.0" encoding="UTF-8"?>
<Speech>
<Item Words="test2" Confidence="2" Semantic="semantic" />
</Speech>
而不是:
<?xml version="1.0" encoding="UTF-8"?>
<Speech>
<Item Words="test" Confidence="1" Semantic="semantic" />
<Item Words="test2" Confidence="2" Semantic="semantic" />
</Speech>
发布于 2014-05-09 15:14:39
如果使用XmlDocument类是必需的,那么我可以建议进行一些增强:
稍作修改的WriteXml
(适用于我):
void WriteXML(string result, float confidence, string semantic, string typeOfSpeech)
{
try
{
//pick whatever filename with .xml extension
string filename = Path.Combine("W:\\", "XMLSpeechOutput.xml");
//if file is not found, create a new xml file
if (!File.Exists(filename))
{
XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("Speech");
xmlWriter.Close();
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
XmlNode root = xmlDoc.DocumentElement;
XmlNode lastWord = root.LastChild;
XmlElement childNode = xmlDoc.CreateElement("Item");
childNode.SetAttribute("Words", result);
childNode.SetAttribute("Confidence", confidence.ToString());
childNode.SetAttribute("Semantic", semantic);
root.InsertAfter(childNode, lastWord);
xmlDoc.Save(filename);
}
catch (Exception ex)
{
WriteError(ex.ToString());
}
}
如果您可以使用另一种技术来访问/修改XML结构,那么我建议您使用LINQ2XML --对于当前的问题,这种使用将减少代码行数。我的示例包含两个扩展方法:
扩展代码:
public static class ProjectExtensions
{
/// <summary>
/// Loads the file with the specified name.
/// If the file does not exist an empty file is created.
/// </summary>
/// <param name="xmlFile">File location with name: c:\xml\input.xml</param>
/// <returns>A filled XDocument object</returns>
public static XDocument CreateOrLoad(this String xmlFile)
{
// if the XML file does not exist
if (!File.Exists(xmlFile))
{
// create an empty file
var emptyXml = new XElement("Speech");
// and save it under the specified name (and location)
emptyXml.Save(xmlFile);
}
// load the file (it was either created or it exists already)
return XDocument.Load(xmlFile);
}
/// <summary>
/// Adds new row at the end of the specified XML document.
/// </summary>
/// <param name="result">TODO</param>
/// <param name="confidence">TODO</param>
/// <param name="semantic">TODO</param>
public static void AppendRow(this XDocument document, string result, float confidence, string semantic, string typeOfSpeech)
{
// prepare/construct the row to add
var row = new XElement("Item", new XAttribute("Word", result),
new XAttribute("Precision", confidence.ToString()),
new XAttribute("Semantic", semantic));
// take the root node
var root = document.Root;
// the xml is empty
if (!root.Elements().Any())
{
// just add the node
root.Add(row);
}
else
{
// add the node after at the end of the file
root.Elements().Last().AddAfterSelf(row);
}
}
}
它可以这样使用:
var filename = "W:\\XMLSpeechOut.xml";
//
var xml = filename.CreateOrLoad();
xml.AppendRow("A", 10.5f, "B", "C");
xml.AppendRow("D", 11.0f, "E", "F");
xml.Save(filename);
// alternative one-liner usage (open or create, append, save)
filename.CreateOrLoad().AppendRow("G", 11.5f, "H", "I").Save(filename);
产出如下:
<?xml version="1.0" encoding="utf-8"?>
<Speech>
<Item Word="A" Precision="10,5" Semantic="B" />
<Item Word="D" Precision="11" Semantic="E" />
<Item Word="G" Precision="11,5" Semantic="H" />
</Speech>
https://stackoverflow.com/questions/23500006
复制相似问题