Search Results

Search found 20 results on 1 pages for 'xpathdocument'.

Page 1/1 | 1 

  • How to estimate memory need by XPathDocument for a specific xml file

    - by bill seacham
    Is there any way to estimate the memory requirement for creating an XpathDocument instance based on the file size of the xml? XpathDocument xdoc = new XpathDocument(xmlfile); Is there any way to programmatically stop the process of creating the XpathDocument if memory drops to a very low level? Since it loads the entire xml into memory, it would be nice to know ahead of time if the xml is too big. What I have found is that when I create a new XpathDocument with a big xml file, an outofmemory exception is never fired, but that the process slows to a crawl, only 5 Mb of memory remains a available and the Task Manager reports it is not responding. This happened with a 266 Mb xml file when there was 584 Mb of ram. I was able to load a 150 Mb file with no problems in 18. After loading the xml, I want to do xpath queries using an XpathNavigator and an XpathNodeIterator. I am using .net 2.0, xp sp3.

    Read the article

  • XPathDocument behavior with DOCTYPE declaration

    - by gliderkite
    I use XPathDocument to parse an XML file, but if there's a doctype declaration, when I initializes a new instance of the XPathDocument class passing the path of the file, that contains the XML data, to its constructor, my application tries to connect to internet (probably to verify the correctness of the XML data) and remains blocked for a long period of time. This does not occur if I delete the doctype declaration from the XML file. XmlDocument.Load method has the same behavior. How can I fix this problem? Thanks.

    Read the article

  • Does an XPathDocument load the whole xml document?

    - by Wires
    If I do XPathDocument doc = new XPathDocument("filename.xml"); Does that load the entire document into memory? I'm writing a mobile phone app and the document might store lots of data that doesn't ever need to all be loaded at the same time. Mobile phones don't usually have too much ram!

    Read the article

  • Parse XML document

    - by Neil
    I am trying to parse a remote XML document (from Amazon AWS): <ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2009-03-31"> <OperationRequest> <RequestId>011d32c5-4fab-4c7d-8785-ac48b9bda6da</RequestId> <Arguments> <Argument Name="Condition" Value="New"></Argument> <Argument Name="Operation" Value="ItemLookup"></Argument> <Argument Name="Service" Value="AWSECommerceService"></Argument> <Argument Name="Signature" Value="73l8oLJhITTsWtHxsdrS3BMKsdf01n37PE8u/XCbsJM="></Argument> <Argument Name="MerchantId" Value="Amazon"></Argument> <Argument Name="Version" Value="2009-03-31"></Argument> <Argument Name="ItemId" Value="603084260089"></Argument> <Argument Name="IdType" Value="UPC"></Argument> <Argument Name="AWSAccessKeyId" Value="[myAccessKey]"></Argument> <Argument Name="Timestamp" Value="2010-06-14T15:03:27Z"></Argument> <Argument Name="ResponseGroup" Value="OfferSummary,ItemAttributes"></Argument> <Argument Name="SearchIndex" Value="All"></Argument> </Arguments> <RequestProcessingTime>0.0318510000000000</RequestProcessingTime> </OperationRequest> <Items> <Request> <IsValid>True</IsValid> <ItemLookupRequest> <Condition>New</Condition> <DeliveryMethod>Ship</DeliveryMethod> <IdType>UPC</IdType> <MerchantId>Amazon</MerchantId> <OfferPage>1</OfferPage> <ItemId>603084260089</ItemId> <ResponseGroup>OfferSummary</ResponseGroup> <ResponseGroup>ItemAttributes</ResponseGroup> <ReviewPage>1</ReviewPage> <ReviewSort>-SubmissionDate</ReviewSort> <SearchIndex>All</SearchIndex> <VariationPage>All</VariationPage> </ItemLookupRequest> </Request> <Item> <ASIN>B0000UTUNI</ASIN> <DetailPageURL>http://www.amazon.com/Garnier-Fructis-Fortifying-Conditioner-Minute/dp/B0000UTUNI%3FSubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB0000UTUNI</DetailPageURL> <ItemLinks> <ItemLink> <Description>Technical Details</Description> <URL>http://www.amazon.com/Garnier-Fructis-Fortifying-Conditioner-Minute/dp/tech-data/B0000UTUNI%3FSubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>Add To Baby Registry</Description> <URL>http://www.amazon.com/gp/registry/baby/add-item.html%3Fasin.0%3DB0000UTUNI%26SubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>Add To Wedding Registry</Description> <URL>http://www.amazon.com/gp/registry/wedding/add-item.html%3Fasin.0%3DB0000UTUNI%26SubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>Add To Wishlist</Description> <URL>http://www.amazon.com/gp/registry/wishlist/add-item.html%3Fasin.0%3DB0000UTUNI%26SubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>Tell A Friend</Description> <URL>http://www.amazon.com/gp/pdp/taf/B0000UTUNI%3FSubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>All Customer Reviews</Description> <URL>http://www.amazon.com/review/product/B0000UTUNI%3FSubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>All Offers</Description> <URL>http://www.amazon.com/gp/offer-listing/B0000UTUNI%3FSubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> </ItemLinks> <ItemAttributes> <Binding>Health and Beauty</Binding> <Brand>Garnier</Brand> <EAN>0603084260089</EAN> <Feature>Helps restore strength and shine</Feature> <Feature>Penetrates deep to nourish, repair and rejuvenate</Feature> <Feature>Makes hair softer and more manageable without weighing it down</Feature> <ItemDimensions> <Weight Units="hundredths-pounds">40</Weight> </ItemDimensions> <Label>Garnier</Label> <ListPrice> <Amount>419</Amount> <CurrencyCode>USD</CurrencyCode> <FormattedPrice>$4.19</FormattedPrice> </ListPrice> <Manufacturer>Garnier</Manufacturer> <NumberOfItems>1</NumberOfItems> <ProductGroup>Health and Beauty</ProductGroup> <ProductTypeName>ABIS_DRUGSTORE</ProductTypeName> <Publisher>Garnier</Publisher> <Size>5.0 oz</Size> <Studio>Garnier</Studio> <Title>Garnier Fructis Fortifying Fortifying Deep Conditioner, 3 Minute Masque - 5 oz</Title> <UPC>603084260089</UPC> </ItemAttributes> <OfferSummary> <LowestNewPrice> <Amount>229</Amount> <CurrencyCode>USD</CurrencyCode> <FormattedPrice>$2.29</FormattedPrice> </LowestNewPrice> <TotalNew>7</TotalNew> <TotalUsed>0</TotalUsed> <TotalCollectible>0</TotalCollectible> <TotalRefurbished>0</TotalRefurbished> </OfferSummary> </Item> </Items> </ItemLookupResponse> I am trying to extract data from the XML stream using XPathDocument, but with no luck: WebRequest request = HttpWebRequest.Create(url); WebResponse response = request.GetResponse(); //XmlDocument doc = new XmlDocument(); XPathDocument Doc = new XPathDocument(response.GetResponseStream()); XPathNavigator nav = Doc.CreateNavigator(); XPathNodeIterator ListPrice = nav.Select("/ItemLookupResponse/Items/Item/ItemAttributes/ListPrice"); foreach (XPathNavigator node in ListPrice) { Response.Write(node.GetAttribute("Amount", NAMESPACE)); } What am I missing? Thanks in advance!!

    Read the article

  • MemoryStream, XmlTextWriter and Warning 4 CA2202 : Microsoft.Usage

    - by rasx
    The Run Code Analysis command in Visual Studio 2010 Ultimate returns a warning when seeing a certain pattern with MemoryStream and XmlTextWriter. This is the warning: Warning 7 CA2202 : Microsoft.Usage : Object 'ms' can be disposed more than once in method 'KinteWritePages.GetXPathDocument(DbConnection)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 421 C:\Visual Studio 2010\Projects\Songhay.DataAccess.KinteWritePages\KinteWritePages.cs 421 Songhay.DataAccess.KinteWritePages This is the form: static XPathDocument GetXPathDocument(DbConnection connection) { XPathDocument xpDoc = null; var ms = new MemoryStream(); try { using(XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8)) { using(DbDataReader reader = CommonReader.GetReader(connection, Resources.KinteRssSql)) { writer.WriteStartDocument(); writer.WriteStartElement("data"); do { while(reader.Read()) { writer.WriteStartElement("item"); for(int i = 0; i < reader.FieldCount; i++) { writer.WriteRaw(String.Format("<{0}>{1}</{0}>", reader.GetName(i), reader[i].ToString())); } writer.WriteFullEndElement(); } } while(reader.NextResult()); writer.WriteFullEndElement(); writer.WriteEndDocument(); writer.Flush(); ms.Position = 0; xpDoc = new XPathDocument(ms); } } } finally { ms.Dispose(); } return xpDoc; } The same kind of warning is produced for this form: XPathDocument xpDoc = null; using(var ms = new MemoryStream()) { using(XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8)) { using(DbDataReader reader = CommonReader.GetReader(connection, Resources.KinteRssSql)) { //... } } } return xpDoc; By the way, the following form produces another warning: XPathDocument xpDoc = null; var ms = new MemoryStream(); using(XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8)) { using(DbDataReader reader = CommonReader.GetReader(connection, Resources.KinteRssSql)) { //... } } return xpDoc; The above produces the warning: Warning 7 CA2000 : Microsoft.Reliability : In method 'KinteWritePages.GetXPathDocument(DbConnection)', object 'ms' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'ms' before all references to it are out of scope. C:\Visual Studio 2010\Projects\Songhay.DataAccess.KinteWritePages\KinteWritePages.cs 383 Songhay.DataAccess.KinteWritePages In addition to the following, what are my options?: Supress warning CA2202. Supress warning CA2000 and hope that Microsoft is disposing of MemoryStream (because Reflector is not showing me the source code). Rewrite my legacy code to recognize the wonderful XDocument and LINQ to XML.

    Read the article

  • .NET XPath Returns No Results

    - by Stacy Vicknair
    When using XPath in .NET one of the gotchas to be aware of is that all namespaces must be named, otherwise you’ll end up with no results. Default namespaces that are specified with xmlns alone still need to be recognized in the XPath query! Say I had a bit of XML like what is returned from the QueryService web service in Sharepoint: 1: <?xml version="1.0" encoding="UTF-8"?> 2: <ResponsePacket xmlns="urn:Microsoft.Search.Response"> 3: <Response> 4: <Range> 5: ... 6: <Results> 7: <Document xmlns="urn:Microsoft.Search.Response.Document" relevance="849"> 8: ...   When consuming and navigating this response with XPath it is necessary to name all namespaces. Then those named namespaces must be used in reference to the individual element being requested (i.e. doc:Document). In VB: 1: Dim xdoc = new XPathDocument(reader) 2: Dim nav = xdoc.CreateNavigator() 3: Dim nsMgr = new XmlNamespaceManager(nav.NameTable) 4: nsMgr.AddNamespace("resp", "urn:Microsoft.Search.Response") 5: nsMgr.AddNamespace("doc", "urn:Microsoft.Search.Response.Document") 6:  7: Dim results = nav.Select("//doc:Document", nsMgr)   In C#: 1: var xdoc = new XPathDocument(reader); 2: var nav = xdoc.CreateNavigator(); 3: var nsMgr = new XmlNamespaceManager(nav.NameTable); 4:  5: nsMgr.AddNamespace("resp", "urn:Microsoft.Search.Response"); 6: nsMgr.AddNamespace("doc", "urn:Microsoft.Search.Response.Document"); 7:  8: var results = nav.Select("//doc:Document", nsMgr);

    Read the article

  • XPathNavigator.Evaluate returning incorrect value?

    - by Eric
    I'm expecting this code to return true but it doesn't ? What am I missing here. string xml = @"<data><e id=""NUM_CPUS"">1</e><e id=""ACE_PRESENT"">1</e></data>"; XPathDocument doc = new XPathDocument(new StringReader(xml)); string expr = "(id('NUM_CPUS'))>=1 and (id('ACE_PRESENT'))=1"; XPathNavigator nav = doc.CreateNavigator(); XPathExpression query = nav.Compile(expr); object result = nav.Evaluate(query); bool b = bool.Parse(result.ToString()); if (!b) throw new Exception("Should be true");

    Read the article

  • Error Installing COM+ (Error Code: 80131501)

    - by Regina Foo
    I've written a class library that reads from an xml file and return the result as a string. But when I want to install it as a COM+ component, an error occurred (Error Code: 80131501). I checked the event log and the details of the error is: Installation of 'C:\Users\User\Documents\Visual Studio 2005\Projects\InteropSOA\InteropSOA\bin\Debug\InteropSOA.dll' into '{28E82165-AD74-4E16-90C9-0C5CE7DA97AA}' failed with an exception: System.EnterpriseServices.RegistrationException: FATAL: Could not find component 'InteropSOA.ConfigReader' we just installed. at System.EnterpriseServices.RegistrationDriver.InstallAssembly(RegistrationConfig regConfig, Object obSync) at System.EnterpriseServices.RegistrationHelper.InstallAssemblyFromConfig(RegistrationConfig& regConfig) at System.EnterpriseServices.RegistrationHelper.InstallAssembly(String assembly, String& application, String partition, String& tlb, InstallationFlags installFlags) at System.EnterpriseServices.Internal.ComManagedImportUtil.InstallAssembly(String asmpath, String parname, String appname) Below are the steps I've done while developing the class library: Added "System.EnterpriseServices" to Reference. Imported the reference to the class. Declared the class as "ServicedComponent". Set project properties ("Make assembly COM-visible" checked, "Register for COM Interop" checked, Signed the assembly with a strong key file name.) Here are my codes: using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.XPath; using System.EnterpriseServices; namespace InteropSOA { public class ConfigReader : ServicedComponent { // xml file name private string strFileName; // type of request private string strRequest = ""; // response string private string strResponse = ""; // declarations for xPath private XPathDocument doc; private XPathNavigator nav; private XPathExpression expr; private XPathNodeIterator iterator; private XmlTextReader reader; private XmlDocument xmlDoc; public ConfigReader(string strFile, string request) { this.strFileName = strFile; this.strRequest = request; } public ConfigReader() { //default contructor } // reader for console program public void ReadXML() { doc = new XPathDocument(strFileName); nav = doc.CreateNavigator(); // compile xPath expression expr = nav.Compile("/Msg/" + strRequest + "/*"); iterator = nav.Select(expr); // interate on the node set try { while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); strResponse += nav2.Value + "|"; } } catch (Exception ex) { Console.WriteLine(ex.Message); } strResponse = strResponse.Substring(0, strResponse.Length-1); Console.WriteLine("Response string = " + strResponse); } public void WriteXML(string strRequest, string strElement, string strValue) { reader = new XmlTextReader(strFileName); xmlDoc = new XmlDocument(); xmlDoc.Load(reader); reader.Close(); XmlNode node; XmlElement root = xmlDoc.DocumentElement; node = root.SelectSingleNode("/Msg/" + strRequest + "/" + strElement); node.InnerText = strValue; xmlDoc.Save(strFileName); } // reader for ASP.NET public string ReadXMLElement() { doc = new XPathDocument(strFileName); nav = doc.CreateNavigator(); // compile xPath expression expr = nav.Compile("/Msg/" + strRequest + "/*"); iterator = nav.Select(expr); // interate on the node set try { while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); strResponse += nav2.Value + "|"; } } catch (Exception ex) { Console.WriteLine(ex.Message); } strResponse = strResponse.Substring(0, strResponse.Length - 1); return strResponse; } } }

    Read the article

  • using xpath get the correct value in selectName

    - by Sangeeta
    Below I have written the code. I need help to get the right value in selectName. I am new to XPath. Basically with this code I am trying to achieve if employeeName = Chris I need to return 23549 to the calling function. Please help. Part of the code: public static string getEmployeeeID(string employeeName) { Cache cache = HttpContext.Current.Cache; string cacheNameEmployee = employeeName + "Tech"; if (cache[cacheNameEpm] == null) { XPathDocument doc = new XPathDocument(HttpContext.Current.Request.MapPath("inc/xml/" + SiteManager.Site.ToString() + "TechToolTip.xml")); XPathNavigator navigator = doc.CreateNavigator(); string selectName = "/Technologies/Technology[FieldName='" + fieldName + "']/EpmId"; XPathNodeIterator nodes = navigator.Select(selectName); if (nodes.Count > 0) { if (nodes.Current.Name.Equals("FieldName")) //nodes.Current.MoveToParent(); //nodes.Current.MoveToParent(); //nodes.Current.MoveToChild("//EpmId"); cache.Add(cacheNameEpm, nodes.Current.Value, null, DateTime.Now + new TimeSpan(4, 0, 0), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); } } return cache[cacheNameEpm] as string; } XML file <?xml version="1.0" encoding="utf-8" ?> <Employees> <Employee> <EName>Chris</EName> <ID>23556</ID> </Employee> <Employee> <EName>CBailey</EName> <ID>22222</ID> </Employee> <Employee> <EName>Meghan</EName> <ID>12345</ID> </Employee> </Employees> PLEASE NOTE:This XML file has 100 nodes. I just put 1 to indicate the structure.

    Read the article

  • how to monitor the program code execution? (file creation and modification by code lines etc)

    - by infant programmer
    My program is about triggering XSL transformation, Its fact that this code for carrying out the transformation, creates some dll and tmp files and deletes them pretty soon after the transformation is completed. It is almost untraceable for me to monitor the creation and deletion of files manually, so I want to include some chunk of codelines to display "which codeline has created/modified which tmp and dll files" in console window. This is the relevant part of the code: string strXmlQueryTransformPath = @"input.xsl"; string strXmlOutput = string.Empty; StringReader srXmlInput = null; StringWriter swXmlOutput = null; XslCompiledTransform xslTransform = null; XPathDocument xpathXmlOrig = null; XsltSettings xslSettings = null; MemoryStream objMemoryStream = null; objMemoryStream = new MemoryStream(); xslTransform = new XslCompiledTransform(false); xpathXmlOrig = new XPathDocument("input.xml"); xslSettings = new XsltSettings(); xslSettings.EnableScript = true; xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); xslTransform.Transform(xpathXmlOrig, null, objMemoryStream); objMemoryStream.Position = 0; StreamReader objStreamReader = new StreamReader(objMemoryStream); strXmlOutput = objStreamReader.ReadToEnd(); // make use of Data in string "strXmlOutput" google and msdn search couldn't help me much..

    Read the article

  • XSLT Transformation of XML File

    - by Russ Clark
    I've written a simple XML Document that I am trying to transform with an XSLT file, but I get no results when I run the code. Here is my XML document: <?xml version="1.0" encoding="utf-8" ?> <Employee xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="XSLT_MVC.Controllers"> <ID>42</ID> <Name>Russ</Name> </Employee> And here is the XSLT file: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:ex="XSLT_MVC.Controllers" > <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <xsl:copy> <!--<xsl:apply-templates select="@* | node()"/>--> <xsl:value-of select="ex:Employee/Name"/> </xsl:copy> </xsl:template> </xsl:stylesheet> Here is the code (from a C# console app) I am trying to run to perform the transform: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; namespace XSLT { class Program { static void Main(string[] args) { Transform(); } public static void Transform() { XPathDocument myXPathDoc = new XPathDocument(@"docs\sampledoc.xml"); XslTransform myXslTrans = new XslTransform(); myXslTrans.Load(@"docs\new.xslt"); XmlTextWriter myWriter = new XmlTextWriter( "results.html", null); myXslTrans.Transform(myXPathDoc, null, myWriter); myWriter.Close(); } } } When I run the code I get a blank html file. I think I may have problems with the namespaces, but am not sure. Can anyone help with this?

    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

  • Searching in XML using Xpath

    - by Sathish
    I have an XML file like below , using xpath and xnavigator how can get the Value of the supplied Tag Attribute for example if i supply RangeName i should get AssumptClient <Validations> <FieldInfo id="1"> <Name>OMID</Name> <Mandatory>Yes</Mandatory> <RangeName>AssumptOMID</RangeName> <DataType>int</DataType> <MaxLength>10</MaxLength> </FieldInfo> <FieldInfo id="2"> <Name>ClientName</Name> <Mandatory>Yes</Mandatory> <RangeName>AssumptClient</RangeName> <DataType>string</DataType> <MaxLength>50</MaxLength> </FieldInfo> <FieldInfo id="3"> <Name>OppName</Name> <Mandatory>Yes</Mandatory> <RangeName>AssumptProjectName</RangeName> <DataType>string</DataType> <MaxLength>50</MaxLength> </FieldInfo> <FieldInfo id="4"> <Name>OperatingGroup</Name> <Mandatory>Yes</Mandatory> <RangeName>AssumptOperatingGroup</RangeName> <DataType>string</DataType> <MaxLength>50</MaxLength> </FieldInfo> </Validations> for now i am using the below code XPathDocument doc; XPathNavigator nav; XPathExpression expr; XPathNodeIterator iterator; doc = new XPathDocument(strConfigFile); nav = doc.CreateNavigator(); expr = nav.Compile("/configuration/Validations/FieldInfo[RangeName='AssumptClient']"); iterator = nav.Select(expr); if (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); textBox1.Text = nav2.GetAttribute("RangeName", ""); }

    Read the article

  • problem with AddSort method

    - by netNewbi3
    Hi Could you let me know what the proboem is with sorting in this code? It doesn't work. My xml: CONTRACTS --CONTRACT ---SUPPLIER ---COMMODITIES ----COMMODITY -----COMODDITYNAME My code: Dim myString As StringBuilder = New StringBuilder(200) Dim xdoc As New XPathDocument("local_xml.xml") Dim nav As XPathNavigator = xdoc.CreateNavigator() Dim expr As XPathExpression expr = nav.Compile("/pf:CONTRACTS/pf:CONTRACT") Dim namespaceManager As XmlNamespaceManager = New XmlNamespaceManager(nav.NameTable) namespaceManager.AddNamespace("pf", "http://namespace.ac.uk/") expr.AddSort("pf:SUPPLIER", XmlSortOrder.Ascending, XmlCaseOrder.None, String.Empty, XmlDataType.Text) expr.SetContext(namespaceManager) Dim nodes As XPathNodeIterator = nav.Select(expr) If nodes.Count > 0 Then myString.AppendLine("<table width='96%' border='0' cellpadding='0' cellspacing='0' border='0' class='datatable1'>") myString.AppendLine("<th width='35%'>Name</th><th width='35%'>Commodity</th><th width='20%'>Supplier</a></th>") While nodes.MoveNext() Dim node As XPathNavigator = nodes.Current.SelectSingleNode("pf:NAME", namespaceManager) Dim supplier As XPathNavigator = nodes.Current.SelectSingleNode("pf:SUPPLIER", namespaceManager) Dim commodity As XPathNavigator = nodes.Current.SelectSingleNode("pf:COMMODITIES/pf:COMMODITY/pf:COMMODITYNAME", namespaceManager) Dim sChars As String = " " myString.AppendLine("<tr>") myString.AppendLine("<td>") myString.AppendLine(node.ToString()) myString.AppendLine("</td>") myString.AppendLine("<td>") myString.AppendLine(commodity.ToString()) myString.AppendLine("</td>") myString.AppendLine("<td>") myString.AppendLine(supplier.ToString()) myString.AppendLine("</td>") myString.AppendLine("</tr>") End While myString.AppendLine("</table>") Dim strOutput As String = myString.ToString() lblOutput.Text = strOutput Else lblOutput.Text = "No results for your search<br/>" End If

    Read the article

  • Authenticating to Google Search Appliance using Basic HTTP auth and ASP.NET (VB)

    - by Chainlink
    I've run into a snag though which has to do with authentication between the Google Search Appliance and ASP. Normally, when asking for secure pages from the search appliance, the search appliance asks for credentials, then uses these credentials to try and access the secure results. If this attempt is successful, the page shows up in the results list. Since ASP is contacting the search appliance on the client's behalf, it will need to collect credentials and pass them along to the search appliance. I have tried a couple of different documented ways of accomplishing this, but they don't seem to work. Below is the code I have tried: 'Bypass SSL since discovery.gov.mb.ca does not have valid SSL cert (NOT PRODUCTION SAFE) ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf customXertificateValidation) googleUrl = "https://removed.com" Dim rdr As New XmlTextReader(googleUrl) Dim resolver As New XmlUrlResolver() Dim myCred As New System.Net.NetworkCredential("USERNAME", "PASSWORD", Nothing) Dim credCache As New CredentialCache() credCache.Add(New Uri(googleUrl), "Basic", myCred) resolver.Credentials = credCache rdr.XmlResolver = resolver doc = New System.Xml.XPath.XPathDocument(rdr) path = doc.CreateNavigator() Private Function customXertificateValidation(ByVal sender As Object, ByVal certificate As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As Net.Security.SslPolicyErrors) As Boolean Return True End Function

    Read the article

  • How do you remove invalid hexadecimal characters from an XML-based data source prior to constructing

    - by Oppositional
    Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML? Note: The solution needs to handle XML data sources that use character encodings other than UTF-8, e.g. by specifying the character encoding at the XML document declaration. Not mangling the character encoding of the source while stripping invalid hexadecimal characters has been a major sticking point. The removal of invalid hexadecimal characters should only remove hexadecimal encoded values, as you can often find href values in data that happens to contains a string that would be a string match for a hexadecimal character. Background: I need to consume an XML-based data source that conforms to a specific format (think Atom or RSS feeds), but want to be able to consume data sources that have been published which contain invalid hexadecimal characters per the XML specification. In .NET if you have a Stream that represents the XML data source, and then attempt to parse it using an XmlReader and/or XPathDocument, an exception is raised due to the inclusion of invalid hexadecimal characters in the XML data. My current attempt to resolve this issue is to parse the Stream as a string and use a regular expression to remove and/or replace the invalid hexadecimal characters, but I am looking for a more performant solution.

    Read the article

  • How to detect the error raised on a particular codeline?

    - by infant programmer
    [Please edit the title if you find its not good enough] I have code which triggers XSL-transformation: objMemoryStream = new MemoryStream(); xslTransform = new XslCompiledTransform(); xpathXmlOrig = new XPathDocument("E:\\xslt error\\Simulation_of_error\\input.xml"); xslSettings = new XsltSettings(); xslSettings.EnableScript = true; xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); xslTransform.Transform(xpathXmlOrig, null, objMemoryStream); objMemoryStream.Position = 0; StreamReader objStreamReader = new StreamReader(objMemoryStream); The method xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); is a victim, which fails some times due to some time-out issue. I want to detect the failure of this codeline and execute again until it successfully executes! I tried using "TRY CATCH and WHILE methods": bool flag = true; do { try { xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); flag = false; } catch { flag = true; } } while (flag); but the problem is "error is getting logged in the log file", Well. The whole code is under one more try statement, which I suspect is writing to log. Which is what I don't want... I don't want end user to know about the failure of this codeline. Is there anyway to get it done?

    Read the article

  • XPathNavigator in Silverlight

    - by vladimir
    I have a code library that makes heavy use of XPathNavigator to parse some specific xml document. The xml document is cross-referenced, meaning that an element can reference another which has not yet been encountered during parsing: <ElementA ...> <DependentElementX id="1234"> </ElementA> <ElementX id="1234" .../> The document doesn't really look like this, but the point is that 1) there is an xml schema that enforces the overall document structure, 2) elements inside the document can reference each other using some IDs, and 3) there is quite a few such cross references between different elements in the document. The document is parsed in two phases. In the first pass I walk through the document XPathDocument doc = ...; XPathNavigator nav = doc.CreateNavigator(); nav.MoveToRoot(); nav.MoveToFirstChild()... and occasionally 'bookmark' the current position (element) in the document using XPathNavigator.Clone() method. This gives me a lightweight instance of an XPathNavigator which I can store somewhere and use later to jump back to a particular place (element) in my document. Once I have enough information collected in the first pass (for example, I have made sure there is indeed an ElementX with an id='1234'), I jump back to saved bookmarks (using those saved XPathNavigators) and complete the parsing. Well, now I'm about to use this library in Silverlight 3.0 and to my horror the XPathNavigator is not in the System.Xml assembly. Questions: 1) Am I missing something obvious (i.e. XPathNavigator does exist in some shape or form, for example in a toolkit or a freeware library)? 2) If I do have to make modifications in the code, what would be the best way to go? Ideally, I would like to make minimal changes, not to rewrite 80% of the code just to be able to use something like XLinq. To resume, in case I have to give up XPathNavigator, all I need is a way to bookmark places in my document and to get back to them so that I can continue to iterate from where I left off. Thanks in advance for any help/ideas.

    Read the article

  • .NET: Is there a way to finagle a default namespace in an XPath 1.0 query?

    - by Cheeso
    I'm building a tool that performs xpath 1.0 queries on XHTML documents. The requirement to use a namespace prefix in the query is killing me. The query looks like this: html/body/div[@class='contents']/div[@class='body']/ div[@class='pgdbbyauthor']/h2[a[@name][starts-with(.,'Quick')]]/ following-sibling::ul[1]/li/a (all on one line) ...which is bad enough, except because it's xpath 1.0, I need to use an explicit namespace prefix on each QName, so it looks like this: ns1:html/ns1:body/ns1:div[@class='contents']/ns1:div[@class='body']/ ns1:div[@class='pgdbbyauthor']/ns1:h2[ns1:a[@name][starts-with(.,'Quick')]]/ following-sibling::ns1:ul[1]/ns1:li/ns1:a To set up the query, I do something like this: var xpathDoc = new XPathDocument(new StringReader(theText)); var nav = xpathDoc.CreateNavigator(); var xmlns = new XmlNamespaceManager(nav.NameTable); foreach (string prefix in xmlNamespaces.Keys) xmlns.AddNamespace(prefix, xmlNamespaces[prefix]); XPathNodeIterator selection = nav.Select(xpathExpression, xmlns); But what I want is for the xpathExpression to use the implicit default namespace. Is there a way for me to transform the unadorned xpath expression, after it's been written, to inject a namespace prefix for each element name in the query? I'm thinking, anything between two slashes, I could inject a prefix there. Excepting of course axis names like "parent::" and "preceding-sibling::" . And wildcards. That's what I mean by "finagle a default namespace". Is this hack gonna work? Addendum Here's what I mean. suppose I have an xpath expression, and before passing it to nav.Select(), I transform it. Something like this: string FixupWithDefaultNamespace(string expr) { string s = expr; s = Regex.Replace(s, "^(?!::)([^/:]+)(?=/)", "ns1:$1"); // beginning s = Regex.Replace(s, "/([^/:]+)(?=/)", "/ns1:$1"); // stanza s = Regex.Replace(s, "::([A-Za-z][^/:*]*)(?=/)", "::ns1:$1"); // axis specifier s = Regex.Replace(s, "\\[([A-Za-z][^/:*\\(]*)(?=[\\[\\]])", "[ns1:$1"); // predicate s = Regex.Replace(s, "/([A-Za-z][^/:]*)(?!<::)$", "/ns1:$1"); // end s = Regex.Replace(s, "^([A-Za-z][^/:]*)$", "ns1:$1"); // edge case s = Regex.Replace(s, "([-A-Za-z]+)\\(([^/:\\.,\\)]+)(?=[,\\)])", "$1(ns1:$2"); // xpath functions return s; } This actually works for simple cases I tried. To use the example from above - if the input is the first xpath expression, the output I get is the 2nd one, with all the ns1 prefixes. The real question is, is it hopeless to expect this Regex.Replace approach to work, as the xpath expressions get more complicated?

    Read the article

1