Quantcast
Channel: XML, System.Xml, MSXML and XmlLite forum
Viewing all 935 articles
Browse latest View live

Can Query remove need for loop ( get attribute if value matches)

$
0
0

I have already downsized my XML fragment to the Node I want.  The code works below (  there are 2 workable approached ) - but I thought I could use LINQ and lamda expression to query from the start - rather than load the dictionary and then clear it if the conditions are not met ( = an attributeName has a specific value ) - ideas ??? 

       public Dictionary<string, string> GetElementAttributesWithKeyByValueCondition(string XMLFragSource, string attribValue, string attribName)
        {  // get all the attributes from the element if attributeValue & attributeName match....

            var myKeyValReturn = new Dictionary<string, string>();
            bool found= false;
            try
            {
                XElement allData = XElement.Parse(XMLFragSource);
                if (allData != null)
                {
                    IEnumerable<XAttribute> telementAttrib = allData.Attributes();
                    foreach (XAttribute xattr in telementAttrib)
                    {
                        myKeyValReturn.Add(xattr.Name.ToString(), xattr.Value);  //&& xattr.Name=attribName)  what's this ? cannot use && ?
                        if (xattr.Name == attribName)
                        {
                            if (xattr.Value == attribValue)
                            { found = true;}
                        }
                    }
                    if (!found)
                    {
                        myKeyValReturn.Clear();
                    }

                      // alternate to bool flag
                      IEnumerable<KeyValuePair<string,string>> kvp=  myKeyValReturn.Where(a=>(a.Value==attribValue && a.Key==attribName));
                      if (kvp.Count()<1)
                      {
                          myKeyValReturn.Clear();  // did not find it.
                      }

                    //  how does this work ??
                    IEnumerable<XAttribute> tAttrib =
                    from a in allData.Attributes()
                    where  a.Value==attribValue
                    select a ;


                }

            }
            catch (Exception e)
            {
                string errorMessage = string.Format("Fn GetElementAttributesWithKeyByValueCondition failed {0},{1}", e.Message, XMLFragSource);

            }

            return myKeyValReturn;

        }

Thanks


andrew


Unable to get elements using XPathSelectElements

$
0
0

Hi,

I have the Xelement as follows.

<root type="object"><meta type="object"><disclaimer type="string">XXXXX</disclaimer><license type="string">http://open.fda.gov/license</license><last_updated type="string">2015-05-31</last_updated></meta><results type="array"><item type="object"><term type="string">Oxygen</term><count type="number">397</count></item><item type="object"><term type="string">Ibuprofen</term><count type="number">301</count></item></results></root>
  IEnumerable<XElement> data = XRoot.XPathSelectElements("/root/results/item/term");

I have tried the above code, to get the array of term element. But i am getting null as the result. I am pretty much sure, that the XPath is correct. But, still i am unable to get.

May i kindly know, whether i am missing something or where i am mistaking???

Thanks in advance.


NANDAKUMAR.T

XML Again XSD: "The element cannot contain text. Content model is empty"

$
0
0

I'm been working on this for the past couple hours and I believe I know the answer to my question, but I'm not sure why. 

 

Problem I have is that I am trying to validate an XML document passed into my web service with an XSD file.  The XSD file was built with the XML designer that comes with VS 2005.  Each time I run the XmlReader class to validate the xml aginst the XSD at the confirmationNumber elemets does the validation raises an error of  "The element cannot contain text. Content model is empty"

 

This one of my unique elements that contain both an attribute and has a inner text value.  My observation is that the validator does not like the mixed attribute/element.  Why I think this way I'm not sure, I've looked around the for any documentation that could be of some value but either there is none, which I believe is highly unlikely or I just did not search enough.

 

What I would hope is someone could give a once over to my XML / Schema if in fact I am doing something wrong or suggestion on how to maintain this mixed attribute/element.

 

 

Tools

Visual Studio 2005

2.0 Frameword

 

XML:

 

      <?xml version=""1.0"" encoding=""utf-8"" ?>
        <message command=""ApplicationRequest"">
            <confirmationNumber Program=""A"">692993</confirmationNumber>
        </message>

 

Schema:

 

<?xml version="1.0" encoding="utf-8"?>
<xsTongue Tiedchema id="DetailReport" xmlns:xs="
http://www.w3.org/2001/XMLSchema">
  <xs:element name="message">
    <xs:complexType>
      <xsTongue Tiedequence>
        <xs:element ref="confirmationNumber" maxOccurs="1" minOccurs="1" />
      </xsTongue Tiedequence>
      <xs:attribute name="command">
        <xsTongue TiedimpleType>
          <xs:restriction base="xsTongue Tiedtring">
            <xs:enumeration value="ApplicationRequest" />
          </xs:restriction>
        </xsTongue TiedimpleType>
      </xs:attribute>
    </xs:complexType>
  </xs:element>
  <xs:element name="confirmationNumber">
    <xs:complexType>
      <xsTongue Tiedequence />
      <xs:attribute name="program">
        <xsTongue TiedimpleType>
          <xs:restriction base="xsTongue Tiedtring">
            <xs:enumeration value="A" />
            <xs:enumeration value="B" />
          </xs:restriction>
        </xsTongue TiedimpleType>
      </xs:attribute>
    </xs:complexType>
  </xs:element>

</xsTongue Tiedchema>

 

 

XElement parser does not ignore entity tokens in attribute value

$
0
0

I have sample XML file:

<?xml version="1.0" encoding="UTF-8"?><root><name id="show_file.php?fid=120983&action=download" /></root>

I use simple C# console application to dump the content of this XML:

static void Main(string[] args)
{
    var xmlPath = @"c:\test.xml";
    var xml = XElement.Load(xmlPath);
    Console.WriteLine(xml.ToString());
}

However, an error occurs:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: '=' is an unexpected token. The expected token is ';'

The error points to "=" sign here "&action=". I looked up the stack trace:

System.Xml.XmlException was unhandled
  HResult=-2146232000
  Message='=' is an unexpected token. The expected token is ';'. Line 67, position 93.
  Source=System.Xml
  LineNumber=67
  LinePosition=93
  SourceUri=""
  StackTrace:
       at System.Xml.XmlTextReaderImpl.Throw(Exception e)
       at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args)
       at System.Xml.XmlTextReaderImpl.ThrowUnexpectedToken(String expectedToken1, String expectedToken2)
       at System.Xml.XmlTextReaderImpl.ThrowUnexpectedToken(Int32 pos, String expectedToken1, String expectedToken2)
       at System.Xml.XmlTextReaderImpl.HandleEntityReference(Boolean isInAttributeValue, EntityExpandType expandType, Int32& charRefEndPos)
       at System.Xml.XmlTextReaderImpl.ParseAttributeValueSlow(Int32 curPos, Char quoteChar, NodeData attr)
       at System.Xml.XmlTextReaderImpl.ParseAttributes()
       at System.Xml.XmlTextReaderImpl.ParseElement()
       at System.Xml.XmlTextReaderImpl.ParseElementContent()
       at System.Xml.XmlTextReaderImpl.Read()
       at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
       at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
       at System.Xml.Linq.XElement.ReadElementFrom(XmlReader r, LoadOptions o)
       at System.Xml.Linq.XElement.Load(XmlReader reader, LoadOptions options)
       at System.Xml.Linq.XElement.Parse(String text, LoadOptions options)
       at System.Xml.Linq.XElement.Parse(String text)
       at ConsoleApp.Program.Main(String[] args) in D:\Projects\ConsoleApp\Program.cs:line 21

The point of interest is System.Xml.XmlTextReaderImpl.HandleEntityReference(Boolean isInAttributeValue, EntityExpandType expandType, Int32& charRefEndPos). As I understand, Xml searches for entity tokens in attribute value. But is it mandatory? I think I can store in attribute value ANY characters and their combinations as far as I use parenthesis. Am I right?


There is no knowledge that is not power.


JS loop with xsl variable

$
0
0

Hi! I having one XML file having a structure like this:

<?xml version="1.0" encoding="utf-8" ?><?xml-stylesheet type="text/xsl" href="temp.xslt" ?><Data><Row><DateAndTime>2015-07-03</DateAndTime><Count>406</Count><Count2>638</Count2></Row><Row><DateAndTime>2015-07-04/DateAndTime><Count>697</Count><Count2>697</Count2></Row></Data>

And for transform using xslt file (temp.xslt) with include javascript like this:

<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="html" version="1.0" encoding="utf-8" indent="yes"/><xsl:template match="/"><html><head><script type="text/javascript"> function showTest() { var rowCount = <xsl:value-of select="count(Data/Row)" /> for(var i = 0; i &lt; rowCount; i++) {<xsl:variable name="nValue">i</xsl:variable> var s1 = <xsl:value-of select="$nValue" /> var passcount = <xsl:value-of select="Data/Row[$nValue]/Count"/>; alert(passcount); } }</script></head><body><input type="button" value="view" onclick="showTest()" /></body></html></xsl:template></xsl:stylesheet>


How I can set index (ex. i in js loop) for <xsl:value-of select="Data/Row[INDEX]/Count"/>.

I tried to use <xsl:value-of select="Data/Row[i]/Count"/> but it's no work.
Any ideas?
Thanks!


Opening client xsd in visual studio crashing visual studio?

$
0
0

I am trying to open xsd in visual studio and its crashing viual studio.

I tried to open xsd in xml editor and able not able to figure out exactly .. but seems like some issue with Grup and sequence

<xs:importnamespace="http://XYZ"schemaLocation="XYZ.xsd"/>

  <xs:redefineschemaLocation="../ABC/123.xsd">

   <xs:groupname="Ptest">

     <xs:sequence>

       <xs:groupref="Ptest"/>

       <xs:groupref="Contents"/>

     </xs:sequence>

   </xs:group>

   <xs:groupname="Test2">

     <xs:sequence>

       <xs:group ref="Test2"/>

       <xs:groupref="SContents"/>

     </xs:sequence>

   </xs:group>

  </xs:redefine>

  <xs:groupname="Contents">

   <xs:sequence>

     <xs:elementref="sdm:Field1"minOccurs="0"maxOccurs="1"/>

     <xs:elementref="sdm:Field2"minOccurs="0"maxOccurs="1"/>

     <xs:elementref="sdm:Field3"minOccurs="0"maxOccurs="1"/>

     <xs:elementref="sdm:Field4"minOccurs="0"maxOccurs="1"/>

     <xs:elementref="sdm:Field5"minOccurs="0"maxOccurs="1"/>

   </xs:sequence>

  </xs:group>

  <xs:groupname="SContents">

   <xs:sequence>

     <xs:elementref="sdm:FieldRef"minOccurs="0"maxOccurs="unbounded"/>

   </xs:sequence>

  </xs:group>

It looks like looping can any one let me know the cuase of crashing visual studio

XSLT to convert XML to CSV

$
0
0

Heya

struggling to convert this piece of xml to csv:

<?xml version="1.0" encoding="utf-8"?><Workbook xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:user="urn:my-scripts" xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"><Worksheet ss:Name="Table1"><Table x:FullColumns="1" x:FullRows="1"><Row><Cell><Data ss:Type="String">Queue Name</Data></Cell><Cell><Data ss:Type="String">Queue Count</Data></Cell></Row><Row><Cell><Data ss:Type="String">LSE02 config for Fast Level 1 B</Data></Cell><Cell><Data ss:Type="Number">237344</Data></Cell></Row><Row><Cell><Data ss:Type="String">LSE02 config for Fast Indices B</Data></Cell><Cell><Data ss:Type="Number">8</Data></Cell></Row><Row><Cell><Data ss:Type="String">LSE02 config for NSX Fast Level 1 B</Data></Cell><Cell><Data ss:Type="Number">0</Data></Cell></Row><Row><Cell><Data ss:Type="String">LSE02 config for NSX Fast Indices B</Data></Cell><Cell><Data ss:Type="Number">1</Data></Cell></Row></Table></Worksheet></Workbook>

desired result is csv  formatted as below

Queue Name,Queue Count

LSE02 config for Fast Level 1 B,237344

LSE02 config for Fast Indices B,8

LSE02 config for NSX Fast Level 1 B,0

LSE02 config for NSX Fast Indices B,1

many thanks in advance

BT


AppendChildNode

$
0
0

I realize this is a rather arcane subject. Still hoping someone can help directly or direct me to a better forum.

I have a project where I create a basic document CustomXMLPart and then need to regularly add (append) childnodes to the document element.  The following code pasted into a standard module will illustrate the basic process.

The .AppendChildNode method doesn't seem to behave correctly.  The MS documentation states that is returns a CustomXMLNode, but direct attempts to do so results in a compile error.

Does anyone see what I might be doing wrong or have a suggestion for a better way?  Thanks.

 

Private m_oXMLPart As CustomXMLPart

Sub BuildDefaultAddressBook()
Dim strXML As String
  On Error Resume Next
  ThisDocument.CustomXMLParts.SelectByNamespace("http://somenamespace/GKM").Item(1).Delete
  On Error GoTo 0
  strXML = "<?xml version='1.0'?>" & vbLf _
    & "<DocumentElement_Test xmlns='http://somenamespace/GKM'>" & vbLf _
    & "</DocumentElement_Test>"
  On Error Resume Next
  Set m_oXMLPart = ThisDocument.CustomXMLParts.SelectByNamespace("http://somenamespace/GKM").Item(1)
  On Error GoTo 0
  If m_oXMLPart Is Nothing Then
    ThisDocument.CustomXMLParts.Add strXML
    Set m_oXMLPart = ThisDocument.CustomXMLParts.SelectByNamespace("http://somenamespace/GKM").Item(1)
  End If
  AddChildNodesInDocumentElement
lbl_Exit:
  Exit Sub
End Sub

Sub AddChildNodesInDocumentElement()
Dim oEntries As CustomXMLNodes, oEntry As CustomXMLNode
Dim oNewEntry As CustomXMLNode
  'Create (add/append) a childnode in the document element
  'According to the MS documentation, AppendChildNode returns a CustomXMLNode
  'However, the following line (stetted out) will not compile, "Compile Error - Expected function or variable"
 
  'Set oNewEntry = m_oXMLPart.DocumentElement.AppendChildNode("Entry", , msoCustomXMLNodeElement)

  'So , I 'm doing it like this:
  m_oXMLPart.DocumentElement.AppendChildNode "Entry", , msoCustomXMLNodeElement
  'Get the colletion of childnodes.
  Set oEntries = m_oXMLPart.SelectNodes("ns0:DocumentElement_Test[1]/*")
  'Get the entry just created which is the last one
  Set oNewEntry = oEntries.Item(oEntries.Count)
  'Now I have my new entry node.
  With oNewEntry
    .AppendChildNode "FirstName", , msoCustomXMLNodeElement, "Greg"
    .AppendChildNode "LastName", , msoCustomXMLNodeElement, "Maxey"
  End With
lbl_Exit:
  Exit Sub
End Sub

Cross posted in Office - Microsoft Answers Programming


Greg Maxey Please visit my website at: http://gregmaxey.mvps.org/word_tips.htm


IXmlSerializable and XmlRoot Prefixes with XmlSerializer

$
0
0

so look here: https://social.msdn.microsoft.com/Forums/en-US/927ac38b-9846-40c0-a1eb-5850553b520d/ixmlserializable-and-prefixes-for-xmlroot-elements?forum=asmxandxml

And it is fundamentally WRONG.

Why?  You can't use XmlElementAttribute on a TYPE.  It only works on properties, fields, etc.  XmlRootAttribute applies to Type.

So:

[XmlRoot("TheClass", Namespace = "http://myelem.com/")]
public class MyClass : IXmlSerializable
{

  [XmlElement("Header", "http://myelem.com/")]
  public HeaderClass Header {get;set;}

}

[Serializable]
public class HeaderClass : IXmlSerializable
{
   [
   public string Name {get;set;}
   public string Value {get;set;}
}

static Main()
{
   XmlSerializerNamespaces xsnNs = new XmlSerializerNamespaces();
   xsnNs.Add("me", "http://myelem.com/");
   XmlSerializer ser = new XmlSerializer(typeof(myClass));
   using (StringWriter sw = new StringWriter(Console.Out))
  {
     ser.Serialize(sw, new MyClass()) {Header = new HeaderClass()}, xmlNs);
  }
}

Now, if in my implementation of IXmlSerializable I call:

 writer.LookupPrefix("http://myelem.com/")

And I get an empty string.

So even the attempt to call writer.WriteElementString(prefix, name, ns, value) doesn't export the prefix in the final xml, because I can't Lookup what the prefix is.  I can look at the property, I can even get the Custom Attribute that provides the Element Name and the Namespace, but I can't get what the prefix for that namespace is without a damned GLOBAL variable.  That defeats the purpose.

That doesn't even bring in the fact that at the start, even providing the XmlSerializerNamespaces collection to the serializer does NOTHING to affect the outcome of the root element.  By the time you get into the call stack for IXmlSerializable.WriteXml() the root element has already been written to the writer.  WITHOUT a prefix. 

If I remove the IXmlSerializable, it outputs correctly.  WHY?  It appears to be a typical case of Microsoft's implementation handicapping developers by doing it one way and eliminating ANY possibility of true polymorphism.  So far I've had to re-write dozens of Microsoft classes from scratch because the originals just don't work the way I need.  And as par for the course, they aren't written in a true OOP fashion which would allow other developers (like myself) to tweak the behavior accordingly. 

It appears XmlSerialization is another scenario that I might have to rewrite EVERYTHING. 
Why have:

XmlSerializer.Serialize(writer, object, XmlSerializerNamespaces)

with a:

XmlWriter.LookupPrefix(namespace)

Which doesn't work!

I gave the prefix to namespace map to the serializer, why can't i look up the prefix from within the writer!!!!!!!!

It's like Microsoft is pulling a Dark Helmet:  "Fooled You!"

If i DON'T use IXmlSerializable XmlSerializer exports accurate xml but not in the format or layout i want.  If I do, i lose xml standard capabilities.  This gives stupidity a whole new level.

A:  I MUST be able to use XmlSerializer
B:  I MUST be able to use IXmlSerializable

Query:

How do I get the two to work in EVERY possible scenario to achieve perfect XML output!

My Conclusion is it can't be done, but that's why i'm posting here in the .0001% chance that there is a solution to this dilemma.

Regards,

Jaeden "Sifo Dyas" al'Raec Ruiner



"Never Trust a computer. Your brain is smarter than any micro-chip."
PS - Don't mark answers on other people's questions. There are such things as Vacations and Holidays which may reduce timely activity, and until the person asking the question can test your answer, it is not correct just because you think it is. Marking it correct for them often stops other people from even reading the question and possibly providing the real "correct" answer.


Different ways of Redefining group in Xsd?

$
0
0

Team,

Can any one let me know the different ways redefining group in xsd.

I am trying to load CDISC schema, but when we are trying to open it on visual studio (tried with different version) crashing/restarting the visual studio. We able to figure out the issue was with redefining the schema group.

<xs:schematargetNamespace="http://www.cdisc.org/ns/odm/v1.3"elementFormDefault="qualified"attributeFormDefault="unqualified"xmlns="http://www.cdisc.org/ns/odm/v1.3"xmlns:xs="http://www.w3.org/2001/XMLSchema"xmlns:sdm="http://www.cdisc.org/ns/studydesign/v1.0">

          

 <xs:importnamespace="http://www.cdisc.org/ns/studydesign/v1.0"schemaLocation="sdm-ns.xsd"/>

 <xs:redefineschemaLocation="../cdisc-odm-1.3.1/ODM1-3-1.xsd">

   <xs:groupname="ProtocolElementExtension">

     <xs:sequence>

       <xs:groupref="ProtocolElementExtension"/>

       <xs:groupref="ProtocolElementContents"/>

     </xs:sequence>

   </xs:group>

   <xs:groupname="StudyEventDefElementExtension">

     <xs:sequence>

       <xs:groupref="StudyEventDefElementExtension"/>

       <xs:groupref="StudyEventDefElementContents"/>

     </xs:sequence>

   </xs:group>

 </xs:redefine>

 

 <xs:groupname="ProtocolElementContents">

   <xs:sequence>

     <xs:elementref="sdm:Summary"minOccurs="0"maxOccurs="1"/>

     <xs:elementref="sdm:InclusionExclusionCriteria"minOccurs="0"maxOccurs="1"/>

     <xs:elementref="sdm:Structure"minOccurs="0"maxOccurs="1"/>

     <xs:elementref="sdm:Workflow"minOccurs="0"maxOccurs="1"/>

     <xs:elementref="sdm:Timing"minOccurs="0"maxOccurs="1"/>

   </xs:sequence>

 </xs:group>

 <xs:groupname="StudyEventDefElementContents">

   <xs:sequence>

     <xs:element ref="sdm:ActivityRef" minOccurs="0" maxOccurs="unbounded"/>

   </xs:sequence>

 </xs:group>

</xs:schema>

Can any one let me know the other option for redefinnig the structure

How to use links in XML?

$
0
0

I got an XML file. I wrote a HTML code that traverses the xml file and outputs it as a tree from the html file

Im trying to figure out how to attach a link to the xml elements, such as when I click on the name in the output, its open a website. I tried:

< Control><![CDATA[<a href='http://www.transientminds.org'>Cli... Here for a demo</a>]]></Control>

Also tried:
< ?xml version="1.0" encoding="UTF-8"?>
< MAIN xmlns:xlink="http://www.w3.org/1999/xlin... MAIN
< MainStation 
        xlink:type="simple" 
        xlink:href="http://google.com"
        xlink:show="new"> Mainstation1
< /MAIN>

both not working

how do i place a hyperlink in xml?

$
0
0
thats it. i googled solutions. tried them. not working

Microsoft Visio 2013 - "DATABASE" ribbon is missing or no longer available...

$
0
0

I need to create a conceptual -> Logical -> Physical models in this order and then generate the DDL Scripts from the physical data model to create the tables in the SQL Server Database. In Visio 2013 doesn’t have the “DATABASE” option in the ribbon? In previous Visio versions, I was be able to generate the DDL Scripts and then export it and create the tables in the SQL Server databases in the past. Now I can’t do that in Visio 2013.  Do you have alternate option for me to do the same things in Visio 2013? Can someone help me to resolve this issue?  I will really appreciate if you can help me with this issue.

Best regards,

Jeannie

"Too Many Arguments To 'Public Overloads Sub New()" Error

$
0
0
Hello, I am just starting out in VB and I was wondering if I could get some help.  I don't understand what this error means "Too Many Arguments to 'Public Overloads Sub New()'.  Here is my code, I am trying to convert input from a textbox into a pdf file as text.  Please help me out.
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports System.IO

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim pdfDoc As New Document()
        Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("Simple.pdf", FileMode.Create))
        Dim teamNameText As TextBox = New TextBox()

        pdfDoc.Open()
        pdfDoc.Add(New TextBox(teamNameText))
        pdfDoc.Close()
    End Sub
End Class


what are back.xml files?

$
0
0
I have Avast as my virus program and recently it has found 12 xml files it cannot open to scan. All files begin with: C:\$Windows.~BT\sources\safeos\safeos.mount\windows\servicing\sessions\  and end with: back.xml  I cannot find these files anywhere on my laptop and I am concerned that these files may be malicious. How can I remove them safely?

xmlserializer ignore non serializable property

$
0
0

i have a report method with an object as a entry, which simply convert the object into the xml string and insert it in a database. the entry objects have wide range and sometimes they includes non serializable properties.

i found this article: link in order to override a XmlSerializer class to ignore the properties. but the problem is I am just part of the big project and i don't know so much about the objects properties and also they increase and changes every day.

now i want to override XmlSerializer to simply ignore the non serializable properties during serialization.(i mean don't throw an exception during serialization and just ignore it and go to the another property.) also here is my serialization method:

XmlSerializer xmlSerializer =newXmlSerializer(instance.GetType());
        using (StringWriter textWriter =newStringWriter()){
            xmlSerializer.Serialize(textWriter, instance);
            str = textWriter.ToString();}

how can i do it?


How to find the right Element

$
0
0

Im new with Linq to XML (but have used Linq to SQL). After some research i have created some code for the below XML 

<?xml version="1.0"?><terms xmlns:xsi="http://www.w3.org/" xmlns:xsd="http://www.w3.org/" name="Hotels"><hotels><hotel name="Hotel 1"><rooms><room reference="123"><availableFrom /><department>External</department><roomofweek>Yes</roomofweek><price_text>50</price_text><priority>Top</priority><room_number>01</room_number><brochure /><room_type>Standard</room_type><rooms /><pictures><picture name="Interior"><filename>1.jpg</filename></picture><picture name="Bathroom"><filename>3.jpg</filename></picture><picture name="Hall way"><filename>2.jpg</filename></picture><picture name="Balcony"><filename>5.JPG</filename></picture></pictures></room><room reference="a123"><availableFrom /><department>External</department><roomofweek>Yes</roomofweek><price_text>100</price_text><priority>Top</priority><room_number>1000</room_number><brochure /><room_type>Executive</room_type><rooms /><pictures><picture name="Interior"><filename>1.jpg</filename></picture><picture name="Bathroom"><filename>3.jpg</filename></picture><picture name="Hall way"><filename>2.jpg</filename></picture><picture name="Balcony"><filename>5.JPG</filename></picture></pictures></room></rooms></hotel><hotel name=" Hotel 2"><rooms><room reference="B3456"><availableFrom /><department>Internal</department><roomofweek>No</roomofweek><price_text>40</price_text><priority>Med</priority><room_number>02</room_number><brochure /><room_type>Economy</room_type><rooms /><pictures><picture name="Interior"><filename>1.jpg</filename></picture><picture name="Bathroom"><filename>3.jpg</filename></picture><picture name="Hall way"><filename>2.jpg</filename></picture><picture name="Balcony"><filename>5.JPG</filename></picture></pictures></room></rooms></hotel></hotels></terms>

To read/load the file

XDocument Xdoc = XDocument.Load(XMLFilePath);
Now i would like to get all the price_text from all individual room:

foreach (var i in Xdoc.Descendants("hotels"))
{
  if (i.Element("price_text").Value == "price_text")

    {
        // Do some data operations
    }
}

But i always get "Additional information: Object reference not set to an instance of an object."?

The idea is to get all the hotels and each individual hotel which has many rooms (which could be 100's) and perform some relevant tasks. How could i resolve this issue?

XSLT Coding issue

$
0
0

Expected outPut:

<?xml version="1.0" encoding="utf-8"?>
http://www.w3.org/2001/XMLSchema-instance" xmlns="SampleXML">
    <Tablix1>
        <SIDCode_Collection>
            <SIDCode SIDCode="854-2013-17011949">
                <PName_Collection>
                    <PName PName="Test1" />
                    <PName PName="Test2" />
                </PName_Collection>
            </SIDCode>
            <SIDCode SIDCode="854-2013-17011950">
                <PName_Collection>
                    <PName PName="Test3" />
                    <PName PName="Test4" />
                </PName_Collection>
            </SIDCode>
        </SIDCode_Collection>
    </Tablix1>

I have written the XSLT code to get the above output. But I am not able to get the output as expected. Can some one please help me to find the issue ?

Currently this is giving only SIDCode. But it is not giving the respective Pname results in the XML output.

                

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:a="SampleXML">
    <xsl:output method="xml" indent="yes" encoding="utf-8"/>

    <xsl:template match="/">
        <xsl:for-each select="a:Report/a:Tablix1/a:SIDCode_Collection/a:SIDCode">
            <xsl:element name="{name(.)}">

                <xsl:for-each select="@SIDCode">
                    <xsl:element name="{name(.)}">
                        <xsl:value-of select="."/>

                        <xsl:for-each select="a:PName_Collection/a:PName">
                                <xsl:element name="{name(.)}">
                                    <xsl:for-each select="@PName">
                                        <xsl:element name="{name(.)}">
                                            <xsl:value-of select="@PName"/>
                                    </xsl:element>
                                </xsl:for-each>
                                </xsl:element>
                        </xsl:for-each>
                    </xsl:element>
                        </xsl:for-each>
                    </xsl:element>
                </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Thank you

Sri

SelectSingleNode Not showing correct data

$
0
0

Hi, 

Whenever we are using "docNode.SelectSingleNode("//im_doc_id").InnerText" it is returning same node value whereas when we are using docNode.SelectSingleNode("im_doc_id").InnerText it is returning correct values.

Same code was earlier file earlier. 

here is the code

Dim xmlDoc As New XmlDocument

        xmlDoc.Load("D:\import.xml")

        Dim docNodes As XmlNodeList
        Dim strCEDocID As String
        Dim strIMDocID As String
        'Dim appPath As String = Application.StartupPath()
        Dim appPath As String = AppDomain.CurrentDomain.BaseDirectory
        docNodes = xmlDoc.SelectNodes("//transaction/documents/document")
        If docNodes.Count = 0 Then

        Else
            For Each docNode In docNodes



                strIMDocID = docNode.SelectSingleNode("//im_doc_id").InnerText
                Dim strDoc As String = docNode.SelectSingleNode("doc_nbr").InnerText
                Console.WriteLine("StrIMDocID :" & strIMDocID)
                Console.WriteLine("DocID :" & strDoc)


            Next

.NET API for OWL/RDF

$
0
0
Hi All,

Just wondering if anyone knows of an API that enables you to create OWL ontologies and also search them.  Looking for an equivalent to the Jena API in Java.

Many thanks,

Pete
Viewing all 935 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>