Trying to open this test file, which exists in a folder under my solution:
C:\dev\trunk\Development\WebSvc\WCFProj\Xml\po.xml
My c# method is :
public XmlDocument generateXmlResponse()
{
string appDir = AppContext.BaseDirectory;
XmlDocument xml = new XmlDocument();
xml.LoadXml(#"Xml\ResponseTempl.xml");
return xml;
}
and the exception message is :
"Data at the root level is invalid. Line 1, position 1."
Now when I step thru the code, I can use the relative path :
appDir + #"Xml\po.xml"
which correctly resolves to:
C:\dev\trunk\Development\WebSvc\WCFProj\Xml\po.xml
and I just took the sample PurchaseOrder.xml from the ms website https://msdn.microsoft.com/en-us/library/bb343181(v=vs.110).aspx :
<PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">
<Address Type="Shipping">
<Name>Ellen Adams</Name>
<Street>123 Maple Street</Street>
<City>Mill Valley</City>
<State>CA</State>
<Zip>10999</Zip>
<Country>USA</Country>
</Address>
<Address Type="Billing">
<Name>Tai Yee</Name>
<Street>8 Oak Avenue</Street>
<City>Old Town</City>
<State>PA</State>
<Zip>95819</Zip>
<Country>USA</Country>
</Address>
<DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes>
<Items>
<Item PartNumber="872-AA">
<ProductName>Lawnmower</ProductName>
<Quantity>1</Quantity>
<USPrice>148.95</USPrice>
<Comment>Confirm this is electric</Comment>
</Item>
<Item PartNumber="926-AA">
<ProductName>Baby Monitor</ProductName>
<Quantity>2</Quantity>
<USPrice>39.98</USPrice>
<ShipDate>1999-05-21</ShipDate>
</Item>
</Items>
</PurchaseOrder>
The issue here is that the following line:
xml.LoadXml(#"Xml\ResponseTempl.xml");
Is trying to load the string as XML and giving you the error as it is invalid XML. LoadXml should be used like so:
xml.LoadXml("<item><name>wrench</name></item>");
Since you are trying to read from a file you need to use:
https://msdn.microsoft.com/en-us/library/875kz807(v=vs.110).aspx
This will look like the following:
xml.Load(#"Xml\ResponseTempl.xml");
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 am trying to figure out how to create a recursive function to read an initial xml document, identical to below.
Every href attribute in these nodes is a link. "" + that href value.
The recursive loop would open an xdoc for each of those.
Notice that some say folder, and some video. i want to create a folder for each folder, a text file for each video listing that href. so nearly identical to the classic recursive example of recursion of a folder/file tree.
Any suggestions? i've tried doing a double set of foreach loops, adding hrefs to lists and then iterating through them but no matter what i try, i never get the folder structure right and if i write a file i always end up overwriting it with whatever comes next.
for reference, it's from playon app and this is the "Recently added" list of netflix.
here's a simple path example that goes from: netflix user -> my list -> a tv show -> tv show seasons ->
Start of folder tree
<group name="Netflix" href="/data/data.xml?id=netflix" type="folder" art="/images/provider.png?id=netflix" searchable="true" id="netflix" childs="0" category="4099">
<group name="Taylor" href="/data/data.xml?id=netflix-73b43a5abf0b4d6086c0a6a2f11200ee" type="folder" childs="0"/>
<group name="Courtney" href="/data/data.xml?id=netflix-00a010f3321f4ca0ae7592a0126995e4" type="folder" childs="0"/>
<group name="Kids" href="/data/data.xml?id=netflix-76d20d377e1f49af9848b2335cb9199f" type="folder" childs="0"/>
<group name="Playback Options" href="/data/data.xml?id=netflix-6b2f5118e04e4072bfe48ab298d4a91f" type="folder" childs="0" art="/images/poster.jpg?id=netflix-6b2f5118e04e4072bfe48ab298d4a91f&size=tiny"/>
</group>
Netflix/Taylor("localhost:54479" + href attribute value)
<group name="Taylor" href="/data/data.xml?id=netflix-73b43a5abf0b4d6086c0a6a2f11200ee" type="folder">
<group name="My List" href="/data/data.xml?id=netflix-98fad8d5a8f348a5b0cb3d7fe6e81ea9" type="folder" childs="0"/>
<group name="Continue Watching" href="/data/data.xml?id=netflix-755b5fb0bb4d4ccab84f92193b7ae10e" type="folder" childs="0"/>
<group name="Browse Genres" href="/data/data.xml?id=netflix-ebc7ba3576dd4cc38acc7478bab3a4ca" type="folder" childs="0"/>
<group name="Just for Kids" href="/data/data.xml?id=netflix-970a14c27f48488188b94d5734797415" type="folder" childs="0"/>
<group name="Top Picks for Taylor" href="/data/data.xml?id=netflix-745bb4c1d2ce43a5aaa24a25bc78f881" type="folder" childs="0"/>
<group name="Recently Added" href="/data/data.xml?id=netflix-0ce59d5a759f4c5c93df8428489c3cff" type="folder" childs="0"/>
<group name="Popular on Netflix" href="/data/data.xml?id=netflix-60802588a871490fa73f13c0ba673a80" type="folder" childs="0"/>
<group name="Suggestions For You" href="/data/data.xml?id=netflix-9491e584db7b4c0c918df7bfbb0e1fe4" type="folder" childs="0"/>
</group>
NetFlix/Taylor/Mylist("localhost:54479"+href attribute value of 'my list' node)
<group name="My List" href="/data/data.xml?id=netflix-98fad8d5a8f348a5b0cb3d7fe6e81ea9" type="folder">
<group name="Africa" href="/data/data.xml?id=netflix-1947c3b0dc91480c8d31f0bfe60194ab" type="folder" childs="0" art="/images/poster.jpg?id=netflix-1947c3b0dc91480c8d31f0bfe60194ab&size=tiny"/>
<group name="Animals Gone Wild" href="/data/data.xml?id=netflix-0793a52b83d746bb8009de611ca48a63" type="folder" childs="0" art="/images/poster.jpg?id=netflix-0793a52b83d746bb8009de611ca48a63&size=tiny"/>
<group name="Ascension" href="/data/data.xml?id=netflix-f6945330c90443f6a889edee09ecd977" type="folder" childs="0" art="/images/poster.jpg?id=netflix-f6945330c90443f6a889edee09ecd977&size=tiny"/>
<group name="The Blue Planet: A Natural History of the Oceans" href="/data/data.xml?id=netflix-b811b457743f4cbbaffc066e01d3e5b5" type="folder" childs="0" art="/images/poster.jpg?id=netflix-b811b457743f4cbbaffc066e01d3e5b5&size=tiny"/>
<group name="Brain Games" href="/data/data.xml?id=netflix-9311dc81e85c4f20a192095c23fd3bf2" type="folder" childs="0" art="/images/poster.jpg?id=netflix-9311dc81e85c4f20a192095c23fd3bf2&size=tiny"/>
<group name="Breaking Bad" href="/data/data.xml?id=netflix-26775c743497400995f6440ef543c99d" type="folder" childs="0" art="/images/poster.jpg?id=netflix-26775c743497400995f6440ef543c99d&size=tiny"/>
<group name="Burn Notice" href="/data/data.xml?id=netflix-645b8cbeb2754f5cb77696298fff5e13" type="folder" childs="0" art="/images/poster.jpg?id=netflix-645b8cbeb2754f5cb77696298fff5e13&size=tiny"/>
<group name="The Road to El Dorado" href="/data/data.xml?id=netflix-c5a76a26075d40408485fa9c2ca0d72b" type="video" art="/images/poster.jpg?id=netflix-c5a76a26075d40408485fa9c2ca0d72b&size=tiny"/>
<group name="The Running Man" href="/data/data.xml?id=netflix-d19265cad13b498ea94a7f9e1b3d145c" type="video" art="/images/poster.jpg?id=netflix-d19265cad13b498ea94a7f9e1b3d145c&size=tiny"/>
</group>
Netflix/Taylor/MyList/Breaking Bad
<group name="Breaking Bad" href="/data/data.xml?id=netflix-26775c743497400995f6440ef543c99d" type="folder" art="/images/poster.jpg?id=netflix-26775c743497400995f6440ef543c99d&size=tiny">
<group name="Season 1" href="/data/data.xml?id=netflix-a5b3b4541e764a3c839638ee6f374e1e" type="folder" childs="0" art="/images/poster.jpg?id=netflix-a5b3b4541e764a3c839638ee6f374e1e&size=tiny"/>
<group name="Season 2" href="/data/data.xml?id=netflix-0116f794675b4e2180aa182e22d4d7d0" type="folder" childs="0" art="/images/poster.jpg?id=netflix-a5b3b4541e764a3c839638ee6f374e1e&size=tiny"/>
<group name="Season 3" href="/data/data.xml?id=netflix-5789d013866b452a858dcc3321f13b5f" type="folder" childs="0" art="/images/poster.jpg?id=netflix-a5b3b4541e764a3c839638ee6f374e1e&size=tiny"/>
<group name="Season 4" href="/data/data.xml?id=netflix-fb480873895548e08f1bcd0e8e6275ce" type="folder" childs="0" art="/images/poster.jpg?id=netflix-a5b3b4541e764a3c839638ee6f374e1e&size=tiny"/>
<group name="Season 5" href="/data/data.xml?id=netflix-65d155a01fd244869fcda5728c7683ad" type="folder" childs="0" art="/images/poster.jpg?id=netflix-a5b3b4541e764a3c839638ee6f374e1e&size=tiny"/>
</group>
the problem is that after it reaches season 5, and goes to the next tv show, i lose the folder tree from Netflix/Taylor/Mylist. the next folder tree would start with the show name and lose anything before it.
private static void addfolder(string url, string parentFolder, string foldertree)
{
string baseurl = null;
string lastFolder;
string path = string.Empty;
string tree = "";
var xdoc = new XmlDocument();
xdoc.Load(url);
// xdoc.Save(Console.Out);
var playonList = new List<Playon>();
foreach (XmlNode groups in xdoc.DocumentElement)
{
if (groups.Attributes[2].Value == "folder")
{
baseurl = "http://localhost:54479";
var netflix = "netflix\\";
path = path + "\\" + groups.Attributes[0].Value.Replace(":", "-");
playonList.Add(new Playon(groups.Attributes[1].Value, groups.Attributes[0].Value,
groups.Attributes[2].Value));
lastFolder = groups.Attributes[0].Value;
Directory.CreateDirectory("C:\\streamertest\\" + path.Replace(":", "-"));
if (File.Exists("C:\\streamertest\\" + path.Replace(":", "-") + "\\data.xml"))
xdoc.Save("C:\\streamertest\\" + path.Replace(":", "-") + "\\data" + groups.Attributes[0] +
".xml");
else
{
xdoc?.Save("C:\\streamertest\\" + path.Replace(":", "-") + "\\data.xml");
}
Console.WriteLine(groups.Attributes[0].Value);
addfolder(baseurl + groups.Attributes[1].Value, lastFolder, path.Replace(":","-"));
}
}
I'm assuming the start of the xml file is like what you posted earlier. The xml identification is the first line and the folder element is the 2nd line. I've been writing recursive methods for 40 years so this is real simple.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string BASE_URL = "http://localhost:54479";
static void Main(string[] args)
{
string url = "/data/data.xml?id=netflix";
string directory = "C:\\streamertest";
string path = "Netflix";
addfolder(path, url, directory, 0);
Console.ReadLine();
}
public static void addfolder(string path, string url, string directory, int level)
{
Console.WriteLine("{0} folder : '{1}'", new string('.', 5 * level), path);
//Directory.CreateDirectory(directory);
XDocument xdoc = XDocument.Load(BASE_URL + url);
XElement root = (XElement)xdoc.FirstNode;
foreach (XElement element in root.Elements())
{
string type = (string)element.Attribute("type");
string name = (string)element.Attribute("name");
string href = (string)element.Attribute("href");
switch (type)
{
case "folder":
string newpath = path + "/" + name;
string newDirectory = directory + "\\" + name;
addfolder(newpath, href, newDirectory, level++);
break;
default:
string pathName = path + "/" + name;
Console.WriteLine("{0} url : '{1}'", new string(' ', 5 * level), pathName);
break;
}
}
}
}
}
I'm struggling to read in a "GPX" file to a WPF (c#) project. Sample GPX is provided below. I've tried a number of different options with the same result.
Document is loading ok, but I'm unable to break it down to access the Nodes Directly.
Any help would be greatly appreciated.
Thanks.
private void Simple_Click(object sender, RoutedEventArgs e)
{
XmlDocument xml = new XmlDocument();
xml.Load(#"C:\Users\Jonathon\Desktop\GPX_Data.gpx");
XmlNodeList nodes = xml.SelectNodes("trkpt"); // have tried: double '/' to get nodes at any level (XPath syntax)
//XmlNodeList nodes = xml.SelectNodes("/gpx/trk/trkseg/trkpt");
int count = 0;
foreach (XmlNode xn in nodes)
{
count++;
}
}
}
Sample GPX File
<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Endomondo.com"
xsi:schemaLocation="http://www.topografix.com/GPX/1/1
http://www.topografix.com/GPX/1/1/gpx.xsd
http://www.garmin.com/xmlschemas/GpxExtensions/v3
http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd
http://www.garmin.com/xmlschemas/TrackPointExtension/v1
http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd"
xmlns="http://www.topografix.com/GPX/1/1"
xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1"
xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<metadata>
<author>
<name>Jonathon Ralfe</name>
<email id="jonathon" domain="ralfe.net"/>
</author>
<link href="http://www.endomondo.com">
<text>Endomondo</text>
</link>
<time>2015-01-27T18:31:26Z</time>
</metadata>
<trk>
<src>http://www.endomondo.com/</src>
<link href="https://www.endomondo.com/workouts/463986953/2256850">
<text>endomondo</text>
</link>
<type>SKIING_DOWNHILL</type>
<trkseg>
<trkpt lat="45.576892" lon="6.894079">
<time>2015-01-26T09:49:57Z</time>
</trkpt>
<trkpt lat="45.576892" lon="6.894079">
<ele>1595.0</ele>
<time>2015-01-26T09:49:59Z</time>
</trkpt>
<trkpt lat="45.577109" lon="6.893946">
<ele>1581.0</ele>
<time>2015-01-26T09:51:46Z</time>
</trkpt>
<trkpt lat="45.5772" lon="6.894084">
<ele>1575.0</ele>
<time>2015-01-26T09:52:02Z</time>
</trkpt>
<trkpt lat="45.577247" lon="6.894212">
<ele>1577.0</ele>
<time>2015-01-26T09:52:05Z</time>
</trkpt>
<trkpt lat="45.577317" lon="6.89452">
<ele>1589.0</ele>
<time>2015-01-26T09:52:11Z</time>
</trkpt>
That's because your xml contains namespaces, so you have to set namespace when querying data.
Consider this approach:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("x", "http://www.topografix.com/GPX/1/1");
XmlNodeList nodes = xml.SelectNodes("//x:trkpt", nsmgr);
Here we're creating NamespaceManager, setting namespace according to your data xmlns="http://www.topografix.com/GPX/1/1" attribute and using this namespace in XPath.
By XPath selection:
foreach(XElement aElement in xml.XPathSelectElements("/trk/trkseg").Elements())
{
foreach(XNode aXNode in aElement.Nodes())
{
//Access subnodes of trkpt
}
}
I am trying to write down a code to read a SOAP Response message and extract values without success.
I am trying to extract scalar values starting at the "structure" node.
Here is my code:
//Extracting the xml http message.
xmlDoc.LoadXml(xmlHttp.responseText);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", "http://messages.ara.algorithmics.com");
nsmgr.AddNamespace("ns2", "http://ws.ara.algorithmics.com");
XmlElement root = xmlDoc.DocumentElement;
XmlNode root1 = root.SelectSingleNode("//structure", nsmgr);
The message is looking like this:
<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<getStructureStatelessResponse xmlns="http://ws.ara.algorithmics.com" xmlns:ns2="http://messages.ara.algorithmics.com">
<contextId>Interactive_CWMAdmin20140828134101_BASE</contextId>
<userId>CWMAdminSimulation_10267</userId>
<parameters>
<aggregation>a:flat</aggregation>
<currency>c:usd</currency>
<depth>2</depth>
<path requestedValue="portfolio://All%20Portfolios/GROUP">portfolio://actual/GROUP</path>
</parameters>
<outputDefs>
<outputDef definitionId="od0">
<outputId>o:Price</outputId>
<annualized>false</annualized>
<currency>c:usd</currency>
<nominalfx>false</nominalfx>
</outputDef>
<outputDef definitionId="od1">
<outputId>o:Value</outputId>
<annualized>false</annualized>
<currency>c:usd</currency>
<nominalfx>false</nominalfx>
</outputDef>
<outputDef definitionId="od2">
<outputId>o:UnitDirtyPrice</outputId>
<annualized>false</annualized>
<currency>c:usd</currency>
<nominalfx>false</nominalfx>
</outputDef>
</outputDefs>
<structure>
<port childCount="316" expandedNodeName="Position View" name="Position View" nodeId="669">
<outputResults>
<scalar ref="od0" value="1.890480805674964E7"/>
<scalar ref="od1" value="1.890480805674964E7"/>
<ratio ref="od2" value="NaN"/></outputResults>
<pos locked="true" name="CF_IF Asset#SPL_ASE#Annuitant mortality improves" nodeId="347" secId="CF_IF Asset#SPL_ASE#Annuitant mortality improves">
<outputResults>
<scalar ref="od0" value="0.0"/><scalar ref="od1" value="0.0"/>
<ratio ref="od2" value="0.0"/></outputResults>
</pos>
<pos locked="true" name="CF_IF Asset#SPL_ASE#Assured lives mortality increases" nodeId="359" secId="CF_IF Asset#SPL_ASE#Assured lives mortality increases">
in the last days i tried to change a value of a single attribute of this application File
The Xml-File:
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd"
manifestVersion="1.0" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1"
xmlns="urn:schemas-microsoft-com:asm.v2"
xmlns:asmv2="urn:schemas-microsoft-com:asm.v2"
xmlns:xrml="urn:mpeg:mpeg21:2003:01-REL-R-NS"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:asmv3="urn:schemas-microsoft-com:asm.v3"
xmlns:dsig="http://www.w3.org/2000/09/xmldsig#"
xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1"
xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2">
<assemblyIdentity name="lolz" version="1.1.1.1" publicKeyToken="12345" language="neutral" processorArchitecture="x86" xmlns="urn:schemas-microsoft-com:asm.v1" />
<description asmv2:publisher="Example" asmv2:product="Productexample2" asmv2:supportUrl="Example" xmlns="urn:schemas-microsoft-com:asm.v1" />
<deployment install="true" mapFileExtensions="true" minimumRequiredVersion="1.1.1.1" trustURLParameters="true">
<subscription>
<update>
<beforeApplicationStartup />
</update>
</subscription>
<deploymentProvider codebase="http://Test" />
</deployment>
</asmv1:assembly>
Here i try to change the value of
<description asmv2:product = "Productexample">
into
<description asmv2:product = "Productexample2">
,and the value of
<deploymentProvider codebase="http://Test" />
into
<deploymentProvider codebase="http://Test2" />
Currently i tried :
private void changeAttribute (string xmlPath)
{
string newValue = "Productexample2";
XmlDocument xmlDoc= new XmlDocument();
xmlDoc.Load(xmlPath);
XmlNode node = xmlDoc.SelectSingleNode("asmv1:assembly/description/asmv2:product");
node.Attributes[0].Value = newValue;
xmlDoc.Save(xmlPath);
}
But it throws the Exception 'An unhandled exception of type 'System.Xml.XPath.XPathException' occurred in System.Xml.dll' so i think asmv1:assembly/description/asmv2:product is wrong ...
any suggestions of code?
as always you can correct me in any way :)
You have to use a namespace manager to make the prefixes work and you need the # character to indicate it is an attribute you are referencing.
So this should work:
XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
manager.AddNamespace("asmv1", "urn:schemas-microsoft-com:asm.v1");
manager.AddNamespace("asmv2", "urn:schemas-microsoft-com:asm.v2");
XmlNode node = xmlDoc.SelectSingleNode("/asmv1:assembly/asmv1:description/#asmv2:product", manager);
Also, your first line in the XML root is incomplete. It should be:
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd"
manifestVersion="1.0"
xmlns:asmv1="urn:schemas-microsoft-com:asm.v1"
xmlns="urn:schemas-microsoft-com:asm.v2"
xmlns:asmv2="urn:schemas-microsoft-com:asm.v2"
xmlns:xrml="urn:mpeg:mpeg21:2003:01-REL-R-NS"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:asmv3="urn:schemas-microsoft-com:asm.v3"
xmlns:dsig="http://www.w3.org/2000/09/xmldsig#"
xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1"
xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2"
>