Search Results

Search found 91 results on 4 pages for 'selectsinglenode'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Relative XPath node selection with C# XmlDocument

    - by lox
    Imagine the following XML document: <root> <person_data> <person> <name>John</name> <age>35</age> </person> <person> <name>Jim</name> <age>50</age> </person> </person_data> <locations> <location> <name>John</name> <country>USA</country> </location> <location> <name>Jim</name> <country>Japan</country> </location> </locations> </root> I then select the person node for Jim: XmlNode personNode = doc.SelectSingleNode("//person[name = 'Jim']"); And now from this node with a single XPath select I would like to retrieve Jim's location node. Something like: XmlNode locationNode = personNode.SelectSingleNode("//location[name = {reference to personNode}/name]"); Since I am selecting based on the personNode it would be handy if I could reference it in the select. Is this possible?.. is the connection there? Sure I could put in a few extra lines of code and put the name into a variable and use this in the XPath string but that is not what I am asking.

    Read the article

  • Call Webservice using Javascript

    - by ajithperuva
    I am trying to call a webservice using javascript.But it shows an error like selectSingleNode() is not a method.I am trying it in mozilla firefox.Which is perfectly working in explorer when i change XMLHttpRequest to ActiveXObject.here i am adding my source code which i am tried in firefox. // Web Service functionality // Global vars var xmlDoc = null; var _serviceCallback = null; // Calls web service, web service url and parms, and callback function or null must be provided. // Callback function receives a true or false based on success of call to host function callWebService(url, callback) { _serviceCallback = callback; if(xmlDoc == null) { // xmlDoc = new XMLHttpRequest(); xmlDoc = new XMLHttpRequest(); } xmlDoc.onreadystatechange = stateChange; //callback for readystate xmlDoc.async = true; //do background processing //xmlDoc.load(url); xmlDoc.open('GET', url); xmlDoc.send(); //var doc= xmlDoc.responseXML; } // Updates readystate by callback function stateChange() { if (xmlDoc.readyState == 4) { var err = xmlDoc.parseError; var result = false; var nd; if(err.errorCode == 0) { nd = xmlDoc.selectSingleNode("//envelope/date_time"); if(nd.text != "") result = true; } // perform callback if provided if(_serviceCallback != null) _serviceCallback(result, nd == null ? "" : nd.text); } } // Callback supplied to XMLHttpRequest call function callbackTest(result, data) { obj = document.getElementById("txtOuput"); if(result) obj.value = "Success " + data; else obj.value = "Web Service Call Failed"; } Please help me...Already which kill my 8 more hours...

    Read the article

  • Modify XML existing content in C#

    - by Nano HE
    Purpose: I plan to Create a XML file with XmlTextWriter and Modify/Update some Existing Content with XmlNode SelectSingleNode(), node.ChildNode[?].InnerText = someting, etc. After I created the XML file with XmlTextWriter as below. XmlTextWriter textWriter = new XmlTextWriter("D:\\learning\\cs\\myTest.xml", System.Text.Encoding.UTF8); I practiced the code below. But failed to save my XML file. XmlDocument doc = new XmlDocument(); doc.Load("D:\\learning\\cs\\myTest.xml"); XmlNode root = doc.DocumentElement; XmlNode myNode; myNode= root.SelectSingleNode("descendant::books"); .... textWriter.Close(); doc.Save("D:\\learning\\cs\\myTest.xml"); I found it is not good to produce like my way. Is there any suggestion about it? I am not clear about the concepts and usage of both XmlTextWriter and XmlNode in the same project. Thank you for reading and replies.

    Read the article

  • Iterating XML nodes using VBA

    - by ydobonmai
    Note:- It just might be a iterating XML nodes using VBA question. Please look at the bottom of this question. It would be good If we can iterate without using MSXML2.DOMDocument I see the this question which answers part of my question on how to retrieve the CustomXMLPart. However, I am not able to iterate through the Xml. That way, this might not be specific to CustomXmlPart, It just might be a iterating XML using VBA question. Following is the XML I have in my CustomXMLPart. <Items> <Item1>Item1</Item1> <Item2>Item2</Item2> <Item3>Item3</Item3> </Items> This is how I add the above XML as CustomXmlPart:- static void AddCustomTableXmlPart(WordprocessingDocument document) { MainDocumentPart mainDocumentPart = document.MainDocumentPart; XDocument itemXml = GetItemsAsCustomXML(); if (mainDocumentPart.GetPartsCountOfType<CustomXmlPart>() > 0) mainDocumentPart.DeleteParts<CustomXmlPart>(mainDocumentPart.CustomXmlParts); //Add a new customXML part and then add content var customXmlPart = mainDocumentPart.AddCustomXmlPart(CustomXmlPartType.CustomXml); //copy the XML into the new part... using (var ts = new StreamWriter(customXmlPart.GetStream())) { ts.Write(itemXml.ToString()); ts.Flush(); } } and this is how I am accessing it in the macro:- Dim itemNode As xmlNode Dim itemChildren As XMLNodes ' The below line throws a run-time error 'Run-time error '13' - 'type mismatch ' not sure why. **Set itemChildren= ActiveDocument.CustomXMLParts(ActiveDocument.CustomXMLParts.Count).SelectSingleNode("//Items").ChildNodes** Interestingly, when I quick watch ActiveDocument.CustomXMLParts(ActiveDocument.CustomXMLParts.Count).SelectSingleNode("//Items").ChildNodes, I see child items in the quick watch window. Is the assignment to the itemChildren variable incorrect? I want to iterate through all the items and get get text for all of them. Could anybody help?

    Read the article

  • Xml Conversion "Type mismatch" Error

    - by prema
    I am selecting a query in sql server 2005 SELECT 'Region' AS ELEMENT,(SELECT GeographyName,GeoID from @tmpTable FOR XML RAW, TYPE) FOR XML RAW('Root') This will give the output in xml as <Root ELEMENT="Region"> <row GeographyName="East" GeoID="2" /> <row GeographyName="West" GeoID="3" /> <row GeographyName="North" GeoID="4" /> <row GeographyName="South" GeoID="5" /> </Root> In aspx page, i want to get this function Populatedata(obj, val) { var xmlDom = new JXmlDom(obj, false); --> at this point i am getting error var nodeHeader = xmlDom.selectNodes("//row"); // my code goes here } function JXmlDom (xml,isFile) { this.load=load; this.loadXML=loadXML; this.selectNodes=selectNodes; this.text=text; this.selectSingleNode=selectSingleNode; this.documentElement=documentElement; this.transformNode=transformNode; if (isFile) { this.dom=this.load (xml); }else { this.dom=this.loadXML (xml); } function loadXML (xml) { if (window.ActiveXObject) { var dom=new ActiveXObject("Microsoft.XMLDOm"); dom.async=false; dom.loadXML (xml); } if (document.implementation && document.implementation.createDocument) { var domParser=new DOMParser(); var dom=domParser.parseFromString (xml,"text/xml"); } return dom; } But when i am calling this i am getting an error as Type mismatch.Can anyone help me

    Read the article

  • Decryption Key value not match

    - by Jitendra Jadav
    public class TrippleENCRSPDESCSP { public TrippleENCRSPDESCSP() { } public void EncryptIt(string sData,ref byte[] sEncData,ref byte[] Key1,ref byte[] Key2) { try { // Create a new TripleDESCryptoServiceProvider object // to generate a key and initialization vector (IV). TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider(); // Create a string to encrypt. // Encrypt the string to an in-memory buffer. byte[] Data = EncryptTextToMemory(sData,tDESalg.Key,tDESalg.IV); sEncData = Data; Key1 = tDESalg.Key; Key2 = tDESalg.IV; } catch (Exception) { throw; } } public string DecryptIt(byte[] sEncData) { //byte[] toEncrypt = new ASCIIEncoding().GetBytes(sEncData); //XElement xParser = null; //XmlDocument xDoc = new XmlDocument(); try { //string Final = ""; string sPwd = null; string sKey1 = null; string sKey2 = null; //System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); string soutxml = ""; //soutxml = encoding.GetString(sEncData); soutxml = ASCIIEncoding.ASCII.GetString(sEncData); sPwd = soutxml.Substring(18, soutxml.LastIndexOf("</EncPwd>") - 18); sKey1 = soutxml.Substring(18 + sPwd.Length + 15, soutxml.LastIndexOf("</Key1>") - (18 + sPwd.Length + 15)); sKey2 = soutxml.Substring(18 + sPwd.Length + 15 + sKey1.Length + 13, soutxml.LastIndexOf("</Key2>") - (18 + sPwd.Length + 15 + sKey1.Length + 13)); //xDoc.LoadXml(soutxml); //xParser = XElement.Parse(soutxml); //IEnumerable<XElement> elemsValidations = // from el in xParser.Elements("EmailPwd") // select el; #region OldCode //XmlNodeList objXmlNode = xDoc.SelectNodes("EmailPwd"); //foreach (XmlNode xmllist in objXmlNode) //{ // XmlNode xmlsubnode; // xmlsubnode = xmllist.SelectSingleNode("EncPwd"); // xmlsubnode = xmllist.SelectSingleNode("Key1"); // xmlsubnode = xmllist.SelectSingleNode("Key2"); //} #endregion //foreach (XElement elemValidation in elemsValidations) //{ // sPwd = elemValidation.Element("EncPwd").Value; // sKey1 = elemValidation.Element("Key1").Value; // sKey2 = elemValidation.Element("Key2").Value; //} //byte[] Key1 = encoding.GetBytes(sKey1); //byte[] Key2 = encoding.GetBytes(sKey2); //byte[] Data = encoding.GetBytes(sPwd); byte[] Key1 = ASCIIEncoding.ASCII.GetBytes(sKey1); byte[] Key2 = ASCIIEncoding.ASCII.GetBytes(sKey2); byte[] Data = ASCIIEncoding.ASCII.GetBytes(sPwd); // Decrypt the buffer back to a string. string Final = DecryptTextFromMemory(Data, Key1, Key2); return Final; } catch (Exception) { throw; } } public static byte[] EncryptTextToMemory(string Data,byte[] Key,byte[] IV) { try { // Create a MemoryStream. MemoryStream mStream = new MemoryStream(); // Create a CryptoStream using the MemoryStream // and the passed key and initialization vector (IV). CryptoStream cStream = new CryptoStream(mStream, new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV), CryptoStreamMode.Write); // Convert the passed string to a byte array. //byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data); byte[] toEncrypt = ASCIIEncoding.ASCII.GetBytes(Data); // Write the byte array to the crypto stream and flush it. cStream.Write(toEncrypt, 0, toEncrypt.Length); cStream.FlushFinalBlock(); // Get an array of bytes from the // MemoryStream that holds the // encrypted data. byte[] ret = mStream.ToArray(); // Close the streams. cStream.Close(); mStream.Close(); // Return the encrypted buffer. return ret; } catch (CryptographicException e) { MessageBox.Show("A Cryptographic error occurred: {0}", e.Message); return null; } } public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV) { try { // Create a new MemoryStream using the passed // array of encrypted data. MemoryStream msDecrypt = new MemoryStream(Data); // Create a CryptoStream using the MemoryStream // and the passed key and initialization vector (IV). CryptoStream csDecrypt = new CryptoStream(msDecrypt, new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV), CryptoStreamMode.Write); csDecrypt.Write(Data, 0, Data.Length); //csDecrypt.FlushFinalBlock(); msDecrypt.Position = 0; // Create buffer to hold the decrypted data. byte[] fromEncrypt = new byte[msDecrypt.Length]; // Read the decrypted data out of the crypto stream // and place it into the temporary buffer. msDecrypt.Read(fromEncrypt, 0, msDecrypt.ToArray().Length); //csDecrypt.Close(); MessageBox.Show(ASCIIEncoding.ASCII.GetString(fromEncrypt)); //Convert the buffer into a string and return it. return new ASCIIEncoding().GetString(fromEncrypt); } catch (CryptographicException e) { MessageBox.Show("A Cryptographic error occurred: {0}", e.Message); return null; } } }

    Read the article

  • XML is case sensitive hence Xml parser (XmlDocument) too...

    - by Narendra Tiwari
    XML is case sensitive hence Xml parser (XmlDocument) too... In below example I am trying to search the <user> element node with name attibute as 'pupu'.  <user name="PuPu" fullname="Priyanka T" email="[email protected]" /> ::translate() functon esures the case insensitive comparision in Xpath expression.   XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("<xml file to load>"); XmlElement userElement = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("//user[translate(@name,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') ='pupu']");

    Read the article

  • Managing common code on Windows 7 (.NET) and Windows 8 (WinRT)

    - by ryanabr
    Recent announcements regarding Windows Phone 8 and the fact that it will have the WinRT behind it might make some of this less painful but I  discovered the "XmlDocument" object is in a new location in WinRT and is almost the same as it's brother in .NET System.Xml.XmlDocument (.NET) Windows.Data.Xml.Dom.XmlDocument (WinRT) The problem I am trying to solve is how to work with both types in the code that performs the same task on both Windows Phone 7 and Windows 8 platforms. The first thing I did was define my own XmlNode and XmlNodeList classes that wrap the actual Microsoft objects so that by using the "#if" compiler directive either work with the WinRT version of the type, or the .NET version from the calling code easily. public class XmlNode     { #if WIN8         public Windows.Data.Xml.Dom.IXmlNode Node { get; set; }         public XmlNode(Windows.Data.Xml.Dom.IXmlNode xmlNode)         {             Node = xmlNode;         } #endif #if !WIN8 public System.Xml.XmlNode Node { get; set ; } public XmlNode(System.Xml.XmlNode xmlNode)         {             Node = xmlNode;         } #endif     } public class XmlNodeList     { #if WIN8         public Windows.Data.Xml.Dom.XmlNodeList List { get; set; }         public int Count {get {return (int)List.Count;}}         public XmlNodeList(Windows.Data.Xml.Dom.XmlNodeList list)         {             List = list;         } #endif #if !WIN8 public System.Xml.XmlNodeList List { get; set ; } public int Count { get { return List.Count;}} public XmlNodeList(System.Xml.XmlNodeList list)         {             List = list;        } #endif     } From there I can then use my XmlNode and XmlNodeList in the calling code with out having to clutter the code with all of the additional #if switches. The challenge after this was the code that worked directly with the XMLDocument object needed to be seperate on both platforms since the method for populating the XmlDocument object is completly different on both platforms. To solve this issue. I made partial classes, one partial class for .NET and one for WinRT. Both projects have Links to the Partial Class that contains the code that is the same for the majority of the class, and the partial class contains the code that is unique to the version of the XmlDocument. The files with the little arrow in the lower left corner denotes 'linked files' and are shared in multiple projects but only exist in one location in source control. You can see that the _Win7 partial class is included directly in the project since it include code that is only for the .NET platform, where as it's cousin the _Win8 (not pictured above) has all of the code specific to the _Win8 platform. In the _Win7 partial class is this code: public partial class WUndergroundViewModel     { public static WUndergroundData GetWeatherData( double lat, double lng)         { WUndergroundData data = new WUndergroundData();             System.Net. WebClient c = new System.Net. WebClient(); string req = "http://api.wunderground.com/api/xxx/yesterday/conditions/forecast/q/[LAT],[LNG].xml" ;             req = req.Replace( "[LAT]" , lat.ToString());             req = req.Replace( "[LNG]" , lng.ToString()); XmlDocument doc = new XmlDocument();             doc.Load(c.OpenRead(req)); foreach (XmlNode item in doc.SelectNodes("/response/features/feature" ))             { switch (item.Node.InnerText)                 { case "yesterday" :                         ParseForecast( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/txt_forecast/forecastdays/forecastday" )), new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/simpleforecast/forecastdays/forecastday" )), data); break ; case "conditions" :                         ParseCurrent( new FishingControls.XmlNode (doc.SelectSingleNode("/response/current_observation" )), data); break ; case "forecast" :                         ParseYesterday( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/history/observations/observation" )),data); break ;                 }             } return data;         }     } in _win8 partial class is this code: public partial class WUndergroundViewModel     { public async static Task< WUndergroundData > GetWeatherData(double lat, double lng)         { WUndergroundData data = new WUndergroundData (); HttpClient c = new HttpClient (); string req = "http://api.wunderground.com/api/xxxx/yesterday/conditions/forecast/q/[LAT],[LNG].xml" ;             req = req.Replace( "[LAT]" , lat.ToString());             req = req.Replace( "[LNG]" , lng.ToString()); HttpResponseMessage msg = await c.GetAsync(req); string stream = await msg.Content.ReadAsStringAsync(); XmlDocument doc = new XmlDocument ();             doc.LoadXml(stream, null); foreach ( IXmlNode item in doc.SelectNodes("/response/features/feature" ))             { switch (item.InnerText)                 { case "yesterday" :                         ParseForecast( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/txt_forecast/forecastdays/forecastday" )), new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/simpleforecast/forecastdays/forecastday" )), data); break; case "conditions" :                         ParseCurrent( new FishingControls.XmlNode (doc.SelectSingleNode("/response/current_observation" )), data); break; case "forecast" :                         ParseYesterday( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/history/observations/observation")), data); break;                 }             } return data;         }     } Summary: This method allows me to have common 'business' code for both platforms that is pretty clean, and I manage the technology differences separately. Thank you tostringtheory for your suggestion, I was considering that approach.

    Read the article

  • Query an XmlDocument without getting a 'Namespace prefix is not defined' problem

    - by Dan Revell
    I've got an Xml document that both defines and references some namespaces. I load it into an XmlDocument object and to the best of my knowledge I create a XmlNamespaceManager object with which to query Xpath against. Problem is I'm getting XPath exceptions that the namespace "my" is not defined. How do I get the namespace manager to see that the namespaces I am referencing are already defined. Or rather how do I get the namespace definitions from the document to the namespace manager. Furthermore tt strikes me as strange that you have to provide a namespace manager to the document which you create from the documents nametable in the first place. Even if you need to hardcode manual namespaces why can't you add them directly to the document. Why do you always have to pass this namespace manager with every single query? What can't XmlDocument just know? The Code: XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(programFiles + @"Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\HfscBookingWorkflow\template.xml"); XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable); XmlNode referenceNode = xmlDoc.SelectSingleNode("/my:myFields/my:ReferenceNumber", ns); referenceNode.InnerXml = this.bookingData.ReferenceNumber; XmlNode titleNode = xmlDoc.SelectSingleNode("/my:myFields/my:Title", ns); titleNode.InnerXml = this.bookingData.FamilyName; ... The Xml: <?xml version="1.0" encoding="UTF-8" ?> <?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:Inspection:-myXSD-2010-01-15T18-21-55" solutionVersion="1.0.0.104" productVersion="12.0.0" PIVersion="1.0.0.0" ?> <?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?> - <my:myFields xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-01-15T18:21:55" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"> <my:DateRequested xsi:nil="true" /> <my:DateVisited xsi:nil="true" /> <my:ReferenceNumber /> <my:FireCall>false</my:FireCall> ...

    Read the article

  • C# XPath id() not working?

    - by Iggyhopper
    I'm using C# and I'm stumped. Does it just not support id()? I have a large XML file, about 4-5 of them at ~400kb, so I need some speed and performance wherever I can get it. I use XmlDocument.SelectSingleNode("id('blahblahblah')") and it doesn't get the node by id. Am I going crazy or is it that C# XPath just doesn't support id()?

    Read the article

  • Problem in SharePoint Object model when accessing the sharepoint list items?

    - by JanardhanReddy
    just i wrote using (SPSite site = SPContext.Current.Site) { using (SPWeb web = site.OpenWeb()) { //SPList lst = web.Lists["ManagerInfo"]; SPList lst = web.Lists[strlist]; SPQuery getUserNameQuery = new SPQuery(); // getUserNameQuery.Query = "<Where><And><Eq><FieldRef Name=\"Region\" /><Value Type=\"Text\">" + strRegion + "</Value></Eq><And><Eq><FieldRef Name=\"PM_x0020_First_x0020_Name\" /><Value Type=\"Text\">" + pmFName + "</Value></Eq><Eq><FieldRef Name=\"PM_x0020_Last_x0020_Name\" /><Value Type=\"Text\">" + pmLname + "</Value></Eq></And></And></Where>"; // getUserNameQuery.Query = "<Where><And><Eq><FieldRef Name=\"PM_x0020_First_x0020_Name\" /><Value Type=\"Text\">" + pmFName + "</Value></Eq><Eq><FieldRef Name=\"PM_x0020_Last_x0020_Name\" /><Value Type=\"Text\">" + pmLname + "</Value></Eq></And></Where>"; getUserNameQuery.Query = "<Where><Eq><FieldRef Name=\"PM_x0020_Name\" /><Value Type=\"Text\">" + loginName + "</Value></Eq></Where>"; SPListItemCollection items = lst.GetItems(getUserNameQuery); foreach (SPListItem item in items) { managerFName = item["Manager Name"].ToString(); strAccounting = item["Accounting"].ToString(); managerFName = managerFName.Replace(".", " "); strAccounting = strAccounting.Replace(".", " "); // isFound = true; XPathNavigator managerName = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtManagerName", NamespaceManager); managerName.SetValue(managerFName); XPathNavigator accountingName = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtAccountingName", NamespaceManager); accountingName.SetValue(strAccounting); } } } i used this code in infopath this infopath is using by all users.os when the current login user have no permissions to the list it showing error.when the current login user have full Permission it is working. So Please advise me what can i do inorder to work them for all users.

    Read the article

  • Need Help About Using XPathNavigator in C#?

    - by Nano HE
    Hello. 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 from <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.

    Read the article

  • Use of text() function when using xPath in dom4j

    - by jlawless
    I have inherited an application that parses xml using dom4j and xPath: The xml being parsed is similar to the following: <cache> <content> <transaction> <page> <widget name="PAGE_ID">WRK_REGISTRATION</widget> <widget name="TRANS_DETAIL_ID">77145</widget> <widget name="GRD_ERRORS" /> </page> <page> <widget name="PAGE_ID">WRK_REGISTRATION</widget> <widget name="TRANS_DETAIL_ID">77147</widget> <widget name="GRD_ERRORS" /> </page> <page> <widget name="PAGE_ID">WRK_PROCESSING</widget> <widget name="TRANS_DETAIL_ID">77152</widget> <widget name="GRD_ERRORS" /> </page> </transaction> </content> </cache> Individual Nodes are being searched using the following: String xPathToGridErrorNode = "//cache/content/transaction/page/widget[@name='PAGE_ID'][text()='WRK_DNA_REGISTRATION']/../widget[@name='TRANS_DETAIL_ID'][text()='77147']/../widget[@name='GRD_ERRORS_TEMP']"; org.dom4j.Element root = null; SAXReader reader = new SAXReader(); Document document = reader.read(new BufferedInputStream(new ByteArrayInputStream(xmlToParse.getBytes()))); root = document.getRootElement(); Node gridNode = root.selectSingleNode(xPathToGridErrorNode); where xmlToParse is a String of xml similar to the excerpt provided above. The code is trying to obtain the GRD_ERROR node for the page with the PAGE_ID and TRANS_DETAIL_ID provided in the xPath. I am seeing an intermittent (~1-2%) failure (returned node is null) of this selectSingleNode request even though the requested node is in the xml being searched. I know there are some gotchas associated with using text()= in xPath and was wondering if there was a better way to format the xPath string for this type of search.

    Read the article

  • need help with xpath expression

    - by geoff swartz
    I have an xml node that looks like <slot highcount="20" lowcount="10" /> I've tried the following xpath expression: XmlNode node = xdoc.SelectSingleNode("slot[@lowcount>=12] && slot[@highcount <=12]"); but I get an invalid token error and I don't have enough experience with this to know what I'm doing wrong. Any ideas?

    Read the article

  • can i perform xml operations in XMLLITE with the same features of MSXML?

    - by Rajakumar
    Hi , I know something about MSXML parser ,to create an xml with native code ..Msxml depends COM..So I want to create xml without com and dom ,so i wish to choose XMLLITE..but i dont know full details about xmllite ,when i was read the xmllite documentation in msdn ,i gathered some points ,they will provide only 2 things (IXMLReader & IxmlWriter).Here in msxml ,i had many functions to do xml operations ,such as selectsinglenode,appendchild ..Now can i perform the same things with XMLLITE?..please give me the right choice towards this ...

    Read the article

  • c# update xml file

    - by Pila
    I want to replace a xml node that is not a child of the root element. how can I do it - not in .Net 3.5? I don't know the exact path to the node I want to replace, I get the node by XPath query like : XmlElement root = doc.DocumentElement; oldItem = root.SelectSingleNode("//Node1[@name='aaa']//Node2[Item='bbb']/Value"); how can I replace this olditem?

    Read the article

  • update XML file

    - by Pila
    I want to replace an XML node that is not a child of the root element. How can I do it - not in .NET 3.5? I don't know the exact path to the node I want to replace, I get the node by XPath query like: XmlElement root = doc.DocumentElement; oldItem = root.SelectSingleNode("//Node1[@name='aaa']//Node2[Item='bbb']/Value"); How can I replace this old item?

    Read the article

  • SSIS: Deploying OLAP cubes using C# script tasks and AMO

    - by DrJohn
    As part of the continuing series on Building dynamic OLAP data marts on-the-fly, this blog entry will focus on how to automate the deployment of OLAP cubes using SQL Server Integration Services (SSIS) and Analysis Services Management Objects (AMO). OLAP cube deployment is usually done using the Analysis Services Deployment Wizard. However, this option was dismissed for a variety of reasons. Firstly, invoking external processes from SSIS is fraught with problems as (a) it is not always possible to ensure SSIS waits for the external program to terminate; (b) we cannot log the outcome properly and (c) it is not always possible to control the server's configuration to ensure the executable works correctly. Another reason for rejecting the Deployment Wizard is that it requires the 'answers' to be written into four XML files. These XML files record the three things we need to change: the name of the server, the name of the OLAP database and the connection string to the data mart. Although it would be reasonably straight forward to change the content of the XML files programmatically, this adds another set of complication and level of obscurity to the overall process. When I first investigated the possibility of using C# to deploy a cube, I was surprised to find that there are no other blog entries about the topic. I can only assume everyone else is happy with the Deployment Wizard! SSIS "forgets" assembly references If you build your script task from scratch, you will have to remember how to overcome one of the major annoyances of working with SSIS script tasks: the forgetful nature of SSIS when it comes to assembly references. Basically, you can go through the process of adding an assembly reference using the Add Reference dialog, but when you close the script window, SSIS "forgets" the assembly reference so the script will not compile. After repeating the operation several times, you will find that SSIS only remembers the assembly reference when you specifically press the Save All icon in the script window. This problem is not unique to the AMO assembly and has certainly been a "feature" since SQL Server 2005, so I am not amazed it is still present in SQL Server 2008 R2! Sample Package So let's take a look at the sample SSIS package I have provided which can be downloaded from here: DeployOlapCubeExample.zip  Below is a screenshot after a successful run. Connection Managers The package has three connection managers: AsDatabaseDefinitionFile is a file connection manager pointing to the .asdatabase file you wish to deploy. Note that this can be found in the bin directory of you OLAP database project once you have clicked the "Build" button in Visual Studio TargetOlapServerCS is an Analysis Services connection manager which identifies both the deployment server and the target database name. SourceDataMart is an OLEDB connection manager pointing to the data mart which is to act as the source of data for your cube. This will be used to replace the connection string found in your .asdatabase file Once you have configured the connection managers, the sample should run and deploy your OLAP database in a few seconds. Of course, in a production environment, these connection managers would be associated with package configurations or set at runtime. When you run the sample, you should see that the script logs its activity to the output screen (see screenshot above). If you configure logging for the package, then these messages will also appear in your SSIS logging. Sample Code Walkthrough Next let's walk through the code. The first step is to parse the connection string provided by the TargetOlapServerCS connection manager and obtain the name of both the target OLAP server and also the name of the OLAP database. Note that the target database does not have to exist to be referenced in an AS connection manager, so I am using this as a convenient way to define both properties. We now connect to the server and check for the existence of the OLAP database. If it exists, we drop the database so we can re-deploy. svr.Connect(olapServerName); if (svr.Connected) { // Drop the OLAP database if it already exists Database db = svr.Databases.FindByName(olapDatabaseName); if (db != null) { db.Drop(); } // rest of script } Next we start building the XMLA command that will actually perform the deployment. Basically this is a small chuck of XML which we need to wrap around the large .asdatabase file generated by the Visual Studio build process. // Start generating the main part of the XMLA command XmlDocument xmlaCommand = new XmlDocument(); xmlaCommand.LoadXml(string.Format("<Batch Transaction='false' xmlns='http://schemas.microsoft.com/analysisservices/2003/engine'><Alter AllowCreate='true' ObjectExpansion='ExpandFull'><Object><DatabaseID>{0}</DatabaseID></Object><ObjectDefinition/></Alter></Batch>", olapDatabaseName));  Next we need to merge two XML files which we can do by simply using setting the InnerXml property of the ObjectDefinition node as follows: // load OLAP Database definition from .asdatabase file identified by connection manager XmlDocument olapCubeDef = new XmlDocument(); olapCubeDef.Load(Dts.Connections["AsDatabaseDefinitionFile"].ConnectionString); // merge the two XML files by obtain a reference to the ObjectDefinition node oaRootNode.InnerXml = olapCubeDef.InnerXml;   One hurdle I had to overcome was removing detritus from the .asdabase file left by the Visual Studio build. Through an iterative process, I found I needed to remove several nodes as they caused the deployment to fail. The XMLA error message read "Cannot set read-only node: CreatedTimestamp" or similar. In comparing the XMLA generated with by the Deployment Wizard with that generated by my code, these read-only nodes were missing, so clearly I just needed to strip them out. This was easily achieved using XPath to find the relevant XML nodes, of which I show one example below: foreach (XmlNode node in rootNode.SelectNodes("//ns1:CreatedTimestamp", nsManager)) { node.ParentNode.RemoveChild(node); } Now we need to change the database name in both the ID and Name nodes using code such as: XmlNode databaseID = xmlaCommand.SelectSingleNode("//ns1:Database/ns1:ID", nsManager); if (databaseID != null) databaseID.InnerText = olapDatabaseName; Finally we need to change the connection string to point at the relevant data mart. Again this is easily achieved using XPath to search for the relevant nodes and then replace the content of the node with the new name or connection string. XmlNode connectionStringNode = xmlaCommand.SelectSingleNode("//ns1:DataSources/ns1:DataSource/ns1:ConnectionString", nsManager); if (connectionStringNode != null) { connectionStringNode.InnerText = Dts.Connections["SourceDataMart"].ConnectionString; } Finally we need to perform the deployment using the Execute XMLA command and check the returned XmlaResultCollection for errors before setting the Dts.TaskResult. XmlaResultCollection oResults = svr.Execute(xmlaCommand.InnerXml);  // check for errors during deployment foreach (Microsoft.AnalysisServices.XmlaResult oResult in oResults) { foreach (Microsoft.AnalysisServices.XmlaMessage oMessage in oResult.Messages) { if ((oMessage.GetType().Name == "XmlaError")) { FireError(oMessage.Description); HadError = true; } } } If you are not familiar with XML programming, all this may all seem a bit daunting, but perceiver as the sample code is pretty short. If you would like the script to process the OLAP database, simply uncomment the lines in the vicinity of Process method. Of course, you can extend the script to perform your own custom processing and to even synchronize the database to a front-end server. Personally, I like to keep the deployment and processing separate as the code can become overly complex for support staff.If you want to know more, come see my session at the forthcoming SQLBits conference.

    Read the article

  • Retrieving a list of eBay categories using the .NET SDK and GetCategoriesCall

    - by Bill Osuch
    eBay offers a .Net SDK for its Trading API - this post will show you the basics of making an API call and retrieving a list of current categories. You'll need the category ID(s) for any apps that post or search eBay. To start, download the latest SDK from https://www.x.com/developers/ebay/documentation-tools/sdks/dotnet and create a new console app project. Add a reference to the eBay.Service DLL, and a few using statements: using eBay.Service.Call; using eBay.Service.Core.Sdk; using eBay.Service.Core.Soap; I'm assuming at this point you've already joined the eBay Developer Network and gotten your app IDs and user tokens. If not: Join the developer program Generate tokens Next, add an app.config file that looks like this: <?xml version="1.0"?> <configuration>   <appSettings>     <add key="Environment.ApiServerUrl" value="https://api.ebay.com/wsapi"/>     <add key="UserAccount.ApiToken" value="YourBigLongToken"/>   </appSettings> </configuration> And then add the code to get the xml list of categories: ApiContext apiContext = GetApiContext(); GetCategoriesCall apiCall = new GetCategoriesCall(apiContext); apiCall.CategorySiteID = "0"; //Leave this commented out to retrieve all category levels (all the way down): //apiCall.LevelLimit = 4; //Uncomment this to begin at a specific parent category: //StringCollection parentCategories = new StringCollection(); //parentCategories.Add("63"); //apiCall.CategoryParent = parentCategories; apiCall.DetailLevelList.Add(DetailLevelCodeType.ReturnAll); CategoryTypeCollection cats = apiCall.GetCategories(); using (StreamWriter outfile = new StreamWriter(@"C:\Temp\EbayCategories.xml")) {    outfile.Write(apiCall.SoapResponse); } GetApiContext() (provided in the sample apps in the SDK) is required for any call:         static ApiContext GetApiContext()         {             //apiContext is a singleton,             //to avoid duplicate configuration reading             if (apiContext != null)             {                 return apiContext;             }             else             {                 apiContext = new ApiContext();                 //set Api Server Url                 apiContext.SoapApiServerUrl = ConfigurationManager.AppSettings["Environment.ApiServerUrl"];                 //set Api Token to access eBay Api Server                 ApiCredential apiCredential = new ApiCredential();                 apiCredential.eBayToken = ConfigurationManager.AppSettings["UserAccount.ApiToken"];                 apiContext.ApiCredential = apiCredential;                 //set eBay Site target to US                 apiContext.Site = SiteCodeType.US;                 return apiContext;             }         } Running this will give you a large (4 or 5 megs) XML file that looks something like this: <soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">    <soapenv:Body>       <GetCategoriesResponse >          <Timestamp>2012-06-06T16:03:46.158Z</Timestamp>          <Ack>Success</Ack>          <CorrelationID>d02dd9e3-295a-4268-9ea5-554eeb2e0e18</CorrelationID>          <Version>775</Version>          <Build>E775_CORE_BUNDLED_14891042_R1</Build> -          <CategoryArray>             <Category>                <BestOfferEnabled>true</BestOfferEnabled>                <AutoPayEnabled>true</AutoPayEnabled>                <CategoryID>20081</CategoryID>                <CategoryLevel>1</CategoryLevel>                <CategoryName>Antiques</CategoryName>                <CategoryParentID>20081</CategoryParentID>             </Category>             <Category>                <BestOfferEnabled>true</BestOfferEnabled>                <AutoPayEnabled>true</AutoPayEnabled>                <CategoryID>37903</CategoryID>                <CategoryLevel>2</CategoryLevel>                <CategoryName>Antiquities</CategoryName>                <CategoryParentID>20081</CategoryParentID>             </Category> (etc.) You could work with this, but I wanted a nicely nested view, like this: <CategoryArray>    <Category Name='Antiques' ID='20081' Level='1'>       <Category Name='Antiquities' ID='37903' Level='2'/> </CategoryArray> ...so I transformed the xml: private void TransformXML(CategoryTypeCollection cats)         {             XmlElement topLevelElement = null;             XmlElement childLevelElement = null;             XmlNode parentNode = null;             string categoryString = "";             XmlDocument returnDoc = new XmlDocument();             XmlElement root = returnDoc.CreateElement("CategoryArray");             returnDoc.AppendChild(root);             XmlNode rootNode = returnDoc.SelectSingleNode("/CategoryArray");             //Loop through CategoryTypeCollection             foreach (CategoryType category in cats)             {                 if (category.CategoryLevel == 1)                 {                     //Top-level category, so we know we can just add it                     topLevelElement = returnDoc.CreateElement("Category");                     topLevelElement.SetAttribute("Name", category.CategoryName);                     topLevelElement.SetAttribute("ID", category.CategoryID);                     rootNode.AppendChild(topLevelElement);                 }                 else                 {                     // Level number will determine how many Category nodes we are deep                     categoryString = "";                     for (int x = 1; x < category.CategoryLevel; x++)                     {                         categoryString += "/Category";                     }                     parentNode = returnDoc.SelectSingleNode("/CategoryArray" + categoryString + "[@ID='" + category.CategoryParentID[0] + "']");                     childLevelElement = returnDoc.CreateElement("Category");                     childLevelElement.SetAttribute("Name", category.CategoryName);                     childLevelElement.SetAttribute("ID", category.CategoryID);                     parentNode.AppendChild(childLevelElement);                 }             }             returnDoc.Save(@"C:\Temp\EbayCategories-Modified.xml");         } Yes, there are probably much cleaner ways of dealing with it, but I'm not an xml expert… Keep in mind, eBay categories do not change on a regular basis, so you should be able to cache this data (either in a file or database) for some time. The xml returns a CategoryVersion node that you can use to determine if the category list has changed. Technorati Tags: Csharp, eBay

    Read the article

  • XPath doesn't work as desired in C#

    - by Nick Brooks
    My code doesn't return the node XmlDocument xml = new XmlDocument(); xml.InnerXml = text; XmlNode node_ = xml.SelectSingleNode(node); return node_.InnerText; // node_ = null !!!!!!!!!!!!!!!!!!! I'm pretty sure my XML and Xpath are correct My Xpath : /ItemLookupResponse/OperationRequest/RequestId' My XML : <?xml version="1.0"?> <ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05"> <OperationRequest> <RequestId>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx</RequestId> .......(the rest of the xml is irrelevant).......... The node my XPath returns is always null for some reason. Can someone help?

    Read the article

  • Select all links from a Html table using XPath (and HtmlAgilityPack)

    - by Adam Asham
    What I am trying to achieve is to extract all links with a href attribute that starts with http://, https:// or /. These links lie within a table (tbody tr td etc) with a certain class. I thought I could specify just the the a element without the whole path to it but it does not seem to work. I get a NullReferenceException at the line that selects the links: var table = doc.DocumentNode.SelectSingleNode("//table[@class='containerTable']"); if (table != null) { foreach (HtmlNode item in table.SelectNodes("a[starts-with(@href, 'https://')]")) { //not working I don't know about any recommendations or best practices when it comes to XPath. Do I create overhead when I query the document two times?

    Read the article

  • RSS parsing last build Date. Fastest way to do so please.

    - by Paul
    Dim myRequest As System.Net.WebRequest = System.Net.WebRequest.Create(url) Dim myResponse As System.Net.WebResponse = myRequest.GetResponse() Dim rssStream As System.IO.Stream = myResponse.GetResponseStream() Dim rssDoc As New System.Xml.XmlDocument() Try rssDoc.Load(rssStream) Catch nosupport As NotSupportedException Throw nosupport End Try Dim rssItems As System.Xml.XmlNodeList = rssDoc.SelectNodes("rss/channel") 'For i As Integer = 0 To rssItems.Count - 1 Dim rssDetail As System.Xml.XmlNode rssDetail = rssItems.Item(0).SelectSingleNode("lastBuildDate") Folks this is what I'm using to parse an RSS feed for the last updated time. Is there a quicker way? Speed seems to be a bit slow on it as it pulls down the entire feed before parsing.

    Read the article

  • RETRIVE XPATH OF AN XML ELELEMNT BY USING ITS VALUE

    - by user299938
    My XmlFile looks like this: <?xml version="1.0"?> <document-inquiry> <publication-reference data-format="docdb" xmlns="http://www.epo.org/exchange"> <document-id> <country>EP</country> <doc-number>2160088</doc-number> <kind>A1</kind> </document-id> </publication-reference> </document-inquiry> For the above xml i need to get the xpath of a specific element say for example "country element" as My Output: "/document-inquiry/publication-reference/document-id/country" My Input : By using its value "EP" This is the code i tried doc.SelectSingleNode("/document-inquiry/publication-reference/document-id[text()='EP']"); I receivev null for the above code. I have to get it using the c# code. Can anyone pls help me on this

    Read the article

  • vbscript xml problem

    - by user181421
    Hello Friends, I have this vbscript that calls a web service written in .net 2010. I'm getting an error at the last line. Can't figure it out. This is the webservice: http://www.kollelbaaleibatim.com/services/getinfo.asmx/GetFronpageInfo Dim xmlDOC Dim bOK Dim J Dim HTTP Dim ImagePathLeftCar, ImagePathRightCar Dim CarIDLeft, CarIDRight Dim ShortTitleLeftCar, ShortTitleRightCar Dim DescriptionLeftCar, DescriptionRightCar Dim PriceLeftCar, PriceRightCar Set HTTP = CreateObject("MSXML2.XMLHTTP") Set xmlDOC =CreateObject("MSXML.DOMDocument") xmlDOC.Async=False HTTP.Open "GET","http://www.kollelbaaleibatim.com/services/getinfo.asmx/GetFronpageInfo", false HTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" HTTP.Send() dim xmldoc2 set xmldoc2 = Server.CreateObject("Microsoft.XMLDOM") xmldoc2.async = False bOK = xmldoc2.load(HTTP.responseXML) if Not bOK then response.write( "Error loading XML from HTTP") end if response.write( xmldoc2.documentElement.xml)'Prints a good looking xml ShortTitleLeftCar = xmldoc2.documentElement.selectSingleNode("LeftCarShortTitle").text 'ERROR HERE

    Read the article

< Previous Page | 1 2 3 4  | Next Page >