so I'm making an project and i been having a problem with a XML replacing some elements after getting from them a texts
i tried a lot of options remove add then new
and XML is like this:
<?xml version="1.0" encoding="utf-8"?>
<UserAccountData>
<user>
<username>Admin</username>
<password>Partyguest12</password>
<ID1>1<stats level="50" HP="1000" exp="250000" /></ID1>
</user>
<user>
<username>2</username>
<password>2</password>
<ID2>2<stats Level="1" HP="20" exp="0" /></ID2>
</user>
<user>
<username>3</username>
<password>3</password>
<ID3>3<stats Level="1" HP="20" exp="0" /></ID3>
</user>
<user>
<username>4</username>
<password>4</password>
<ID4>4<stats Level="1" HP="20" exp="0" /></ID4>
</user>
<user>
<username>5</username>
<password>5</password>
<ID5>5<stats Level="1" HP="20" exp="0" /></ID5>
</user>
</UserAccountData>
public partial class Game : MetroFramework.Forms.MetroForm
{
private void Save_data_Progress_Click(object sender, EventArgs e)
{
int IDcheck = 0;
XmlDocument User_Data_Exp_Use = new XmlDocument();
User_Data_Exp_Use.Load("UserData.xml");
foreach (XmlNode ID_Finder in User_Data_Exp_Use.SelectNodes("UserAccountData/user"))
{
IDcheck++;
if ((Account.Text == ID_Finder.SelectSingleNode("username").InnerText) && (Log_In_Data.PassKey == ID_Finder.SelectSingleNode("password").InnerText))
{
break;
}
}
XmlNode User_Path = User_Data_Exp_Use.SelectSingleNode("UserAccountData/user/ID" + IDcheck);
XmlElement Stats_Set = User_Data_Exp_Use.CreateElement("stats");
Stats_Set.SetAttribute("Level", Lv.Text);
Stats_Set.SetAttribute("HP", Hit_Points.Text);
Stats_Set.SetAttribute("exp",XP.Text);
User_Path.AppendChild(Stats_Set);
User_Data_Exp_Use.Save("UserData.xml");
}
}
it got me nothing or one of the XML error after run, saying its NULL
Related
I recreated a minimal example from GitHub's SpeechRecognitionAndSynthesis from the Scenario_SRGSConstraint.xaml.cs scenario using the grammar I created in an xml file called grammar.
What I would like to solve would be the sequence of words with which to start the action. I recreated the model so that I could choose two colors: red and green for a rectangle background.
Now what I have to say (I will use words in Italian by necessity) to start the action after pressing the button I must pronounce the color first, between red and green and then background to start the action.
I would like to be able to pronounce the background first (then sfondo) and then the color (then rosso o verde), I tried in various ways to modify the grammar.xml several times without success.
I wanted to ask at this point what changes I have to make to start the action by saying the sentence for example: red background or green background ... so as to pronounce the word background (then sfondo) first and then red or green (then rosso o verde) word.
Finally I would like to ask if I need to change only the grammar.xml or even the Code Behind.
MainPage.xaml.cs:
private SpeechRecognizer speechRecognizer;
private IAsyncOperation<SpeechRecognitionResult> recognitionOperation;
private ResourceContext speechContext;
private ResourceMap speechResourceMap;
private Dictionary<string, Color> colorLookup = new Dictionary<string, Color>
{
{ "COLOR_RED", Colors.Red }, {"COLOR_GREEN", Colors.Green}
};
public MainPage()
{
InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
if (permissionGained)
{
Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
string langTag = speechLanguage.LanguageTag;
speechContext = ResourceContext.GetForCurrentView();
speechContext.Languages = new string[] { langTag };
speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
await InitializeRecognizer();
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
if (speechRecognizer != null)
{
if (speechRecognizer.State != SpeechRecognizerState.Idle)
{
if (recognitionOperation != null)
{
recognitionOperation.Cancel();
recognitionOperation = null;
}
}
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
}
private async Task InitializeRecognizer()
{
if (speechRecognizer != null)
{
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
try
{
string languageTag = SpeechRecognizer.SystemSpeechLanguage.LanguageTag;
StorageFile grammarFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///grammar.xml"));
speechRecognizer = new SpeechRecognizer(SpeechRecognizer.SystemSpeechLanguage);
speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
SpeechRecognitionGrammarFileConstraint grammarConstraint = new SpeechRecognitionGrammarFileConstraint(grammarFile);
speechRecognizer.Constraints.Add(grammarConstraint);
SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync();
}
catch (Exception ex) { string message = ex.Message; }
}
private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
{
}
private async void RecognizeWithoutUI_Click(object sender, RoutedEventArgs e)
{
try
{
recognitionOperation = speechRecognizer.RecognizeAsync();
SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
{
HandleRecognitionResult(speechRecognitionResult);
}
}
catch (TaskCanceledException exception)
{
System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
System.Diagnostics.Debug.WriteLine(exception.ToString());
}
}
/// <summary>
/// Uses the result from the speech recognizer to change the colors of the shapes.
/// </summary>
/// <param name="recoResult">The result from the recognition event</param>
private void HandleRecognitionResult(SpeechRecognitionResult recoResult)
{
// Check the confidence level of the recognition result.
if (recoResult.Confidence == SpeechRecognitionConfidence.High ||
recoResult.Confidence == SpeechRecognitionConfidence.Medium)
{
if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BACKGROUND") && recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString() != "...")
{
string backgroundColor = recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString();
colorRectangle.Fill = new SolidColorBrush(getColor(backgroundColor));
}
}
}
/// <summary>
/// Creates a color object from the passed in string.
/// </summary>
/// <param name="colorString">The name of the color</param>
private Color getColor(string colorString)
{
Color newColor = Colors.Transparent;
if (colorLookup.ContainsKey(colorString))
{
newColor = colorLookup[colorString];
}
return newColor;
}
grammar.xml:
<?xml version="1.0" encoding="utf-8" ?>
<grammar xml:lang="it-IT" root="colorChooser"
tag-format="semantics/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">
<rule id="background_Color">
<item>
<item>
<ruleref uri="#color"/>
</item>
sfondo
</item>
</rule>
<rule id="colorChooser">
<one-of>
<item>
<item>
<ruleref uri="#background_Color"/>
<tag> out.KEY_BACKGROUND=rules.latest(); </tag>
</item>
</item>
</one-of>
</rule>
<rule id="color">
<one-of>
<item>
rosso <tag> out="COLOR_RED"; </tag>
</item>
<item>
verde <tag> out="COLOR_GREEN"; </tag>
</item>
</one-of>
</rule>
</grammar>
Thanks in advance for the help.
--Update--
With this setting it is wrong ... I also tried to set playCommands with items that have exit tags but it does not run correctly (I update my post to highlight my test with your suggestion) The problem is that " out.KEY_BACKGROUND = rules.latest (); " must be inserted somewhere to start the action because in the code behind it is executed through this key: KEY_BACKGROUND.
Codice grammar.xml provato da me con il tuo suggerimento:
<?xml version="1.0" encoding="utf-8" ?>
<grammar xml:lang="it-IT" root="playCommands"
tag-format="semantics/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">
<rule id="background_Color">
<item>
sfondo
</item>
</rule>
<rule id="playCommands">
<item>
<ruleref uri="#background_Color" />
</item>
<item>
<ruleref uri="#color" />
<tag> out.KEY_BACKGROUND=rules.latest(); </tag>
</item>
</rule>
<rule id="color">
<one-of>
<item>
rosso <tag> out="COLOR_RED"; </tag>
</item>
<item>
verde <tag> out="COLOR_GREEN"; </tag>
</item>
</one-of>
</rule>
</grammar>
--Update1--
I tried your code and I think that the grammar.xml logic is correct, but in the code behind it gives me an error here:
recognitionOperation = speechRecognizer.RecognizeAsync();
In the method RecognizeWithoutUI_Click
And the error is this:
The text associated with this error code could not be found.
Here is the complete project: Test Grammar UWP
If you want to the elements must be listed in the order that the user will speak the command, you can create a top-level rule element that references both the background and color rules to create a flexible collection of commands, And set the command to be the root, like below:
grammar.xml:
<grammar xml:lang="it-IT" root="playCommands"
tag-format="semantics/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">
<rule id="background_Color">
<item>
sfondo
</item>
</rule>
<rule id="playCommands">
<ruleref uri="#background_Color" />
<ruleref uri="#color" />
</rule>
<rule id="color">
<one-of>
<item>
rosso <tag> out="COLOR_RED"; </tag>
</item>
<item>
verde <tag> out="COLOR_GREEN"; </tag>
</item>
</one-of>
</rule>
</grammar>
Update:
If you want to use "out.KEY_BACKGROUND = rules.latest();" You just need to change the position of the sfondo and <ruleref uri="#color"/>. In this case, it will execute the backgroundColor first and then the color.
<?xml version="1.0" encoding="utf-8" ?>
<grammar xml:lang="it-IT" root="colorChooser"
tag-format="semantics/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">
<rule id="background_Color">
<item>
sfondo
<item>
<ruleref uri="#color"/>
</item>
</item>
</rule>
<rule id="colorChooser">
<item>
<ruleref uri="#background_Color"/>
<tag> out.KEY_BACKGROUND=rules.latest(); </tag>
</item>
</rule>
<rule id="color">
<one-of>
<item>
rosso <tag> out="COLOR_RED"; </tag>
</item>
<item>
verde <tag> out="COLOR_GREEN"; </tag>
</item>
</one-of>
</rule>
</grammar>
I have this XML file:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfPasswordSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<PasswordSettings>
<CustomerRef>c</CustomerRef>
<Node>n</Node>
<Name>na</Name>
<Login>l</Login>
<Password>ITra+Map1RxklmcSY5yOo9wU9tUV0S4C4qwUv4p2ZFS3L8ByJYXmA9YjswlSTjQZXUJAkV3Z6mhY8OF5/dFOLNAZZRk2i2IOzrVOWSDfdpB8/Vm7PPF0ucSHILHNWpT8</Password>
<FileType>ft</FileType>
</PasswordSettings>
<PasswordSettings>
<CustomerRef>c</CustomerRef>
<Node>n</Node>
<Name>na</Name>
<Login>l</Login>
<Password>ITra+Map1RxklmcSY5yOo9wU9tUV0S4C4qwUv4p2ZFS3L8ByJYXmA9YjswlSTjQZXUJAkV3Z6mhY8OF5/dFOLNAZZRk2i2IOzrVOWSDfdpB8/Vm7PPF0ucSHILHNWpT8</Password>
<FileType>ft</FileType>
</PasswordSettings>
</ArrayOfPasswordSettings>
As you see there are multiple <PasswordSettings> which is a list of multiple items like name, login and password. Can I iterate the <PasswordSettings> in some foreach <PasswordSettings> loop and get the elements?
Please try with this example :
XML:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<Brand name="Brand1">
<product name="Product1" />
<product name="Product2" />
</Brand>
<Brand name="Brand2">
<product name="Product3" />
<product name="Product4" />
</Brand>
</root>
C#:
StringBuilder result = new StringBuilder();
foreach (XElement level1Element in XElement.Load(#"D:\product.xml").Elements("Brand"))
{
result.AppendLine(level1Element.Attribute("name").Value);
foreach (XElement level2Element in level1Element.Elements("product"))
{
result.AppendLine(" " + level2Element.Attribute("name").Value);
}
}
Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication108
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var results = doc.Descendants("PasswordSettings").Select(x => new
{
c = (string)x.Element("CustomerRef"),
node = (string)x.Element("Node"),
name = (string)x.Element("Name"),
login = (string)x.Element("Login"),
password = (string)x.Element("Password"),
fileType = (string)x.Element("FileType")
}).ToList();
}
}
}
This is the code I used.
private void button1_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Load("XMLDatabase.xml");
var NumberExist = doc.Descendants("Users")
.Any(x => (string)x.Element("ID") == txtId.Text);
if (NumberExist)
{
MessageBox.Show("Number already exist");
}
}
My Xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users>
<User Name="aa" Occupation="dd" Date_Of_Birth="123456" NIC="123123" ID="79461" />
<User Name="Ali Rasheed" Occupation="Student" Date_Of_Birth="111694" NIC="4550246607037" ID="12661" />
<User Name="Asif Rasheed" Occupation="Civil Engineer" Date_Of_Birth="241190" NIC="4550346603073" ID="90939" />
</Users>
First, there is no ID element in Users, It belongs to User.
Second, ID is not an Element, It's an Attribute.
Therefore, you should change your code like this:
var NumberExist = doc.Descendants("User")
.Any(x => (string)x.Attribute("ID") == txtId.Text);
This question already has an answer here:
Error: "The node to be inserted is from a different document context"
(1 answer)
Closed 8 years ago.
I am using XML as discuss forum in ASP.NET. I am trying to add functionality for updating comments. My XML structure is this:
<forum>
<author id="1">
<comment id="0" idUser="19">
<name>....</name>
<date>....</date>
<message>...</message>
</comment>
<comment id="1" idUser="4">
....
</comment>
</author>
<author id="2">
....
</author>
</forum>
And my code is:
protected void btnEditComment_Click(object sender, EventArgs e)
{
if (messageTxb.Text!="" && nameTxb.Text!="")
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/App_Data/forum.xml"));
XmlNode newComment = (XmlNode)Session["Comment"];
XmlNode oldComment = doc.SelectSingleNode(string.Format("//author[#id={0}]/comment[#id={1}]",Request.QueryString["id"],newComment.Attributes["id"].Value));
newComment.ChildNodes[0].InnerText = nameTxb.Text.Trim();
newComment.ChildNodes[1].InnerText = string.Format("{0:D}", DateTime.Now);
newComment.ChildNodes[2].InnerText = messageTxb.Text.Trim();
oldComment.ParentNode.ReplaceChild(newComment, oldComment);
doc.Save(Server.MapPath("~/App_Data/forum.xml"));
Repeater1.DataBind();
Response.Redirect(string.Format("~/user/Autor.aspx?id={0}", Request.QueryString["id"]));
}
}
I get error
'The node to be inserted is from a different document context.'
It raises when I am trying to use the replaceChild method.
try to replace this row:
oldComment.ParentNode.ReplaceChild(doc.ImportNode(newComment, true), oldComment);
My XML file as below. It mixed schema and normal elements.
<?xml version="1.0" encoding="utf-8"?>
<!-- R1 -->
<ax:root xmlns:ax="http://amecn/software/realtime/ax">
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="EquipmentConstants">
<xsd:complexType>
<xsd:sequence>
<xsd:element minOccurs="0" maxOccurs="unbounded" ref="EquipmentConstant" />
</xsd:sequence>
</xsd:complexType>
<xsd:unique name="id">
<xsd:selector xpath=".//EquipmentConstant" />
<xsd:field xpath="#id" />
</xsd:unique>
</xsd:element>
......
......
</xsd:schema>
<EquipmentConstants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<EquipmentConstant id="0">
<Name>SerialNumber</Name>
<Group>SYSTEM</Group>
<Data>
<Value min="0" max="10000000" scale_factor="0" unit="U_NO_UNITS" permission="NolimitedAndNoChangeable" type="xsd_string" enum="" flag="0">0</Value>
</Data>
<Description>Serial Number</Description>
</EquipmentConstant>
.....
.....
</EquipmentConstants>
</ax:root>
My C# code as below. I want to loop the elements start from (by pass all the content of schema)
<EquipmentConstants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
XPathDocument doc = new XPathDocument("test.xml");
XPathNavigator navigator = doc.CreateNavigator();
navigator.MoveToRoot(); // <?xml version="1.0" encoding="utf-8"?>
//navigator.MoveToFirstChild(); // <!-- R1 -->
// 1st, I tried to use MoveToChield(), But I failed to move there.
navigator.MoveToChild("EquipmentConstants");
// Then, I also tried to use SelectSingleNode(). But I failed too.
navigator.SelectSingleNode("ax/EquipmentConstants");
while (navigator.MoveToNext())
{
// do something.
}
Could you please give me some suggestion. Thank you.
XPathNavigator navigator = doc.CreateNavigator();
if (navigator == null)
{
return;
}
foreach (XPathNavigator nav in
navigator.Select("/" + "EquipmentConstants" + "/" + "EquipmentConstant"))
{
}
My solution as below.
XPathDocument doc = new XPathDocument("test.xml");
XPathNavigator navigator = doc.CreateNavigator();
navigator.MoveToRoot(); // <?xml version="1.0" encoding="utf-8"?>
navigator.MoveToFirstChild(); // <!-- R1 -->
navigator.MoveToNext(); // <ax:root xmlns:ax="http://amecn/software/realtime/ax">
navigator.MoveToChild("EquipmentConstants", ""); // <EquipmentConstants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
navigator.MoveToFirstChild(); // <EquipmentConstant id="0">
do
{
// Loop body;
} while (navigator.MoveToNext());