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

XML Transform using XSLT when simple type is repeating

$
0
0

Hi,

I am trying to transform one xml to another xml using xslt transform.
when there is a complex node repeating then all nodes are properly transformed and things are fine.
If the simple type is repeating then same count of nodes are transformed but value of all nodes are value of the very first node.

This is a part of xml

    <GetDataResult xmlns="http://tempuri.org/">
        <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">0</string>
        <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">1</string>
        <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">2</string>
        <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">3</string>
    </GetDataResult>


this is my Xslt snippet part

    <response>
        <xsl:for-each select="ns1:GetDataResponse/ns1:GetDataResult/ns2:string" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
            <item>
                <xsl:value-of select="/ns1:GetDataResponse/ns1:GetDataResult/ns2:string/text()" />
            </item>
        </xsl:for-each>
    </response>

i tried few combinations of Xslt for each loop, however the final result is as below. all the items have value of the first repeating node.

    <?xml version="1.0" encoding="utf-16"?>
    <Fields>
        <response>
            <item>0</item>
            <item>0</item>
            <item>0</item>
            <item>0</item>
        </response>
    </Fields>

this it transformation code snippet.

        XmlDocument xslDoc = new XmlDocument();
        xslDoc.InnerXml = XsltCode;
        System.Xml.Xsl.XslTransform xslTransform = new System.Xml.Xsl.XslTransform();
        StringWriter xmlResult = new StringWriter();
        try
        {
            //Load XSL Transform Object
            xslTransform.Load(xslDoc, new XmlUrlResolver(), null);
            //Load the xsl parameter if Any
            System.Xml.Xsl.XsltArgumentList xslArgs = new System.Xml.Xsl.XsltArgumentList();
            //Call the actual Transform method
            xslTransform.Transform(xmlDoc, null, xmlResult, new XmlUrlResolver());
        }
        catch
        { }
        string firstParse = xmlResult.ToString();

Regards,

 Harish


xsd element maxOccurs ignored by readXMLSchema

$
0
0

Hello,

I have the following issue: when I load xsd definition into a dataset (ds.readXMLSchema) it seems to ignore maxOccurs parameter for userdefined datatypes.

when parsing this data
<EmployeeCode>0841</EmployeeCode>
<EmployeeCode>0842</EmployeeCode>

with this declaration
<xs:element minOccurs="0" maxOccurs="unbounded" name="EmployeeCode" type="xs:string">

it is parsed fine: separate table is created and both values are there.

BUT with this declaration
<xs:element minOccurs="0" maxOccurs="unbounded" name="EmployeeCode" type="mydefenition:string_max_8">
where
 <xs:simpleType name="string_max_8">
    <xs:restriction base="xs:string">
      <xs:maxLength value="8"/>
    </xs:restriction>
  </xs:simpleType> 

a new column is added to the table representing parent node and populated with the first value


Can someone help, please?

Change xsi type in XML file?

$
0
0

Hello,

Is it possible to programmatically go through an XML file and change what the xsi:type is equal to, especially if there are multiple xsi:type assignments in a single XML file?

Change xsi type in XML file?

$
0
0

Hello,

Is it possible to programmatically go through an XML file and change what the xsi:type is equal to, especially if there are multiple xsi:type assignments in a single XML file?

XSLT - Using C# Function and Entity Framework

$
0
0

Hi,

I have a number of functions in an xsl file that all work ok. They are basic C# functions.

Now I need to create a method that uses Entity Framework to return data from SQL Server table.

However, when I add it into the xsl functions I get error...

Error 1 Metadata file 'myAssemblyName.dll' could not be found 

Below is my code...

<msxsl:script language="C#" implements-prefix="userCSharp"><msxsl:assembly name="System.Core" /><msxsl:using namespace="System.Linq" /><msxsl:using namespace="System.Collections.Generic" /><msxsl:assembly name="myAssemblyName" /><msxsl:using namespace="myAssemblyNamespace" /><![CDATA[
public string GetMappingValue(string name, string value)
{
    using (Entities entities = new Entities())
    {
        try
        {
            List<MappingValue> mappedValues = (from c in entities.GetMappedValue(name, value)
                                                select c).ToList();

            return mappedValues[0].ValidValue;
        }
        catch (Exception exception)
        {
            _logger.Error("An exception occurred while getting value.", exception);
            throw;
        }
    }
}

Thanks!

XML to JSON with custom column names

$
0
0

HI experts,

In below i need to convert that xml to defined json.

I mean my xml source Load_Number should be converted to load-nbr with that value.

So i will receive an xml document and i need to convert that to json in a efficient way.

<TN_TestData><Load_Number>9436394</Load_Number><Location_Code>PNCT</Location_Code></TN_TestData>

   {"load-nbr":"9436394","loc-code":"PNCT"}


XSLT Linq Query Error

$
0
0

Hi,

I have a method in an xsl file, which uses Entity Framework to load data from SQL Server.

The method works fine when I test it in a C# class. The only error I get is...

XslLoadException was caught:
) expected

I don't see any missing bracket. I replaced the try/catch block to: return "test";

This worked fine. So I am not sure what is wrong with the Linq query?

Code...

<msxsl:script language="C#" implements-prefix="userCSharp"><msxsl:assembly href="C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll" /><msxsl:using namespace="System.Linq" /><msxsl:using namespace="System.Collections.Generic" /><msxsl:assembly href="C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Entity.dll" /><msxsl:using namespace="System.Data.Entity" /><msxsl:assembly href="C:\myAssembly.dll" /><msxsl:using namespace="myAssembly" /><![CDATA[
public string GetMappingValue(string name, string value)
{
    using (Entities entities = new Entities())
    {
        try
        {
            var mappedValues = (from c in entities.GetMappedValue(name, value)
                                                select c).FirstOrDefault();
            return mappedValues.ToString();
        }
        catch (Exception exception)
        {
            throw;
        }
    }
}

]]></msxsl:script>


XSL-FO external-graphic not showing uri is not recognized

$
0
0
Issue

Load a image using the
fo:external-graphic tag.

  I have a parameter with the base64 value of the image.

    <xsl:param name="Name">data:image/jpg;base64,/9j/4AAQSkZJRgA..</xsl:param>


 
I have tried to load the image using   

   
<fo:external-graphic src="{$Name}" width="40mm" height="18.25mm" >                            </fo:external-graphic>


Error

I get  an error uri is not recognizederror



  [1]: http://i.stack.imgur.com/KsK1n.png.
XSLT

    <?xml version="1.0" encoding="utf-8"?>    <xsl:stylesheet version="1.0"  xmlns:m="http://www.ibm.com/maximo"                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"                    xmlns:fo="http://www.w3.org/1999/XSL/Format" >      <xsl:output method="xml" version="1.0" encoding="UTF-8"  indent="yes" />                  <xsl:param name="Name">data:image/jpg;base64,/9j/dddds....ghP/Z</xsl:param>      <xsl:template match="/">        <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">              <fo:layout-master-set>            <fo:simple-page-master master-name="hello"                        page-height="11in"  page-width="8.5in" margin-top="1in"                        margin-bottom="1in" margin-left="1in" margin-right="1in">              <fo:region-body margin-top="1in" margin-bottom=".5in"/>            </fo:simple-page-master>          </fo:layout-master-set>              <fo:page-sequence master-reference="hello">            <fo:flow flow-name="xsl-region-body">              <fo:block font-size="18pt" text-align="center" font-weight="bold">                Hello World!                           <fo:external-graphic src="{$Name}"/>              </fo:block>            </fo:flow>          </fo:page-sequence>            </fo:root>      </xsl:template>    </xsl:stylesheet>


 I am using Fonet.dll


Replacing Values in an XML

$
0
0

Hi,

I have an Xml file that has some values (InnerText) that has been encrypted. I have the decript tool which accepts the InnerText of the element (not an attribute) and a password.

Here is the approximate xml structure:

<?xml version="1.0" encoding="UTF-8"?><Configuration Version="2.2"><Globals xmlns="http://www.site.com"><DataFrameResizable Value="True"/><DataFrameMinWidth Value="360"/><HomePanelContent><![CDATA[ <p style="text-align: center">Text...</p> ]]></HomePanelContent></Globals><Modules><AdvancedSearch LibraryId="LibraryId"><Views><View Visible="false" Id="AdvancedSearchView" Type="AdvancedSearchView" Region="DataRegion"/></Views><Configuration><searches><search><ID>0</ID><name>Equipment</name><description/><searchfields><field><ID>0</ID><name>88CntWQzzOp72jT3r8hpHw==</name>  <--- THIS LINE<mandatory>True</mandatory><fieldtype>TextBox</fieldtype><parametersComboBox><parameters><selecttable>MMtAGQM3bk3KyfcZa6MoXA==</selecttable><valuecolumn>MMtAGQM3bk3KyfcZa6MoXA==</valuecolumn></parameters></parametersComboBox></field><field>
							SOME MORE ELEMENTS HERE</field></searchfields></search></searches></Configuration></AdvancedSearch></Modules></Configuration>

I have indicated on the xml one of the lines that has to have its value decrypted (<-- THIS LINE) but there are a couple more on the file.

Also the xml is dynamic, meaning it can have more elements that are not present at this time.

Now what I need is to create a dynamic method in C# preferably that iterates through everything and replaces only the encrypted text.

I know I can do that by referencing the tags and using xelement or xpath but the issue is I need to make it dynamic.

Can anyone help me please?

If needed I will provide further info.

Thanks in advance

Prevent XML eXternal Entity (XXE) attack during deserialization

$
0
0

We are doing  security analysis of our code using veracode and its showing XXE flaw for below code, specifically where Deserialize() is invoked. How can we prevent serializer from accessing external entities. My attempt below is not working.

public

staticT DeserializeObject(stringxml,stringNamespace)

        {

            System.Xml.Serialization.

XmlSerializerserializer =newSystem.Xml.Serialization.XmlSerializer(typeof(T), Namespace);

           

MemoryStreamstream =

                   

newMemoryStream(Encoding.Default.GetBytes(xml));

           

XmlReaderSettingssettings =newXmlReaderSettings();

           

// allow entity parsing but do so more safely


            settings.DtdProcessing =

DtdProcessing.Ignore;

            settings.XmlResolver =

null;

           

using(XmlReaderreader = XmlReader.Create(stream, settings))

            {

               

returnserializer.Deserialize(reader)asT;

            }

        }


Create a element programatically

$
0
0

When I want to create an element with xsl:name prefix in C#, it creates a element without xsl prefix. How can I create an element with specific prefix? I removed header from xml file, but when I opened the xml file, Load method had thrown an exception about xsl prefix.

<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="text" omit-xml-declaration="yes" indent="no"/><table border="1"><thead><tr><!--<th><span><xsl:text>HeaderSample</xsl:text></span></th>--></tr></thead><tbody><xsl:for-each select="result1"><xsl:for-each select="row"><tr><td><xsl:for-each select="HeaderSample"><xsl:apply-templates/></xsl:for-each></td></tr></xsl:for-each></xsl:for-each></tbody></table></xsl:stylesheet>				 						

XmlDocument doc = new XmlDocument();
        doc.Load("Template\\ResultItem.xml");

        XmlNode headerElement =     doc.LastChild.SelectSingleNode("table/thead/tr");

        foreach (string h in Headers)
        {
            XmlElement thElement = doc.CreateElement("th");
            XmlElement spanElement = doc.CreateElement("span");
            XmlElement xslTextElement = doc.CreateElement("xsl:text");

            xslTextElement.InnerText = h;

            spanElement.AppendChild(xslTextElement);
            thElement.AppendChild(spanElement);
            headerElement.AppendChild(thElement);
        }

In the output there is no <xsl:text>...</xsl:text> but there is <text>...</text>.

XPath doesn't point the right element

$
0
0

I have an XML source that I load it in c# by XmlDocument. I need to access one element in this source that this element uses a prefix called xsl. When I've tried to get the element with XPath command, the right element isn't returned. Instead, other element that have xsl prefix returned. I tested the XPath command in XMLSpy and it works correctly.

<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><table border="1"><thead><tr><!--<th><span><xsl:text>HeaderSample</xsl:text></span></th>--></tr></thead><tbody><!--I need the below element--><xsl:for-each select="result1"><xsl:for-each select="row"><tr><td><xsl:for-each select="HeaderSample"><xsl:apply-templates/></xsl:for-each></td></tr></xsl:for-each></xsl:for-each></tbody></table></xsl:stylesheet>				 						

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");

            XmlNode resultName = doc.LastChild.SelectSingleNode("table/tbody/xsl:for-each[1]", nsmgr);

How can I fix it?


Transforming xml using transformNodeToObject throwing error "Not enough storage is available to complete this operation" .

$
0
0

Transforming xml using transformNodeToObject method as below using VB Script:

OS:Windows Server 2012;
MSXML 6.0

Dim oData
set oData = createobject("MSXML2.DOMDocument.6.0")
With oData
.Async = False
If Not .LoadXML(DataNode) Then alert "Cannot load DataNode.  " & .parseError.reason
End With

dim oTmp
Set oTmp= createobject("MSXML2.DOMDocument.6.0") 

oData.transformNodeToObject style,oTmp 

I am getting the below error in Windows Server 2012.

-2147024882 Not enough storage is available to complete this operation.

This error is occurring only in Windows Server 2012. The above code is working fine with Windows 7 (MSXML). I have noticed the product name of msxml6.dll in Windows 7 is  MSXML 6.0 SP3 and it is Microsoft XML Core Services in Windows Server 2012. Also I have noticed the task manager, it is taking more memory in Windows Server 2012

The above code is working fine in all lower version of OS except Windows Server 2012. Please give the solution for this.

(XSLT 1.0) Question about mapping substrings as attributes of an element

$
0
0

Hello,

Let's say I have this block of xml that will be transformed into another xml using XSLT.

<ComboBox><parameter><sqlexpression>SELECT  DISTINCT Type FROM TABLE where typecode = {0} and typename ={1}</sqlexpression></parameter></ComboBox>

Where {0} and {1} are parameters.

I need to pass them as attributes to the parameter element like this:

<parameter variables"0,1"></parameter>

If there are indeed parameters in the sqlexpression I need to create an attribute called "variables" and for each of them write them inside that attribute.

If only {0} then variables="0"

If {0} and {1} then variables="0,1"

and so on.

I've tried doing something with substring-after and substring-before, but obviously I can't get more than one instance on the same string.

Can anyone hlep me?

Thanks in advance and if needed I will try to provide further information.


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


For an valid XML getting error as "There is an error in XML document (1, )" while De-serializing for the first time

$
0
0

For an valid XML getting error as "There is an error in XML document (1, )" while De-serializing for the first time and again if re-run the same XML successfully getting De-serialized.

Can anyone help me on fixing this issue. Below is the code 

using (StreamReader xmlDocument = new StreamReader(file.FullName))
   {
XmlSerializer serializer = new XmlSerializer(typeof(PatientUpdate));
PatientUpdate objPatientUpdate = (PatientUpdate)serializer.Deserialize(xmlDocument); == Here i m geeting the error
xmlDocument.Close();

Unable to get xml array

$
0
0

Hi Friends,

 Dim str As String = "<?xml version='1.0'?><catalog><things><gadgets>Watch</gadgets></things><book><Novel><price>10</price></Novel><Novel><price>15</price></Novel></book></catalog>"
        Dim catalog As catalog = New catalog()

        Dim serializer As New XmlSerializer(GetType(catalog))
        Using reader As TextReader = New StringReader(str)
            catalog = serializer.Deserialize(reader)
            Dim bookprice As String = catalog.book(0).price

        End Using

Public Class catalog
    Private thingsField As catalogThings
    Private bookField() As catalogNovel

    Public Property things() As catalogThings
        Get
            Return Me.thingsField
        End Get
        Set(value As catalogThings)
            Me.thingsField = value
        End Set
    End Property
 
    Public Property book() As catalogNovel()
        Get
            Return Me.bookField
        End Get
        Set(value As catalogNovel())
            Me.bookField = value
        End Set
    End Property
End Class

Public Class catalogThings
    Private gadgetsField As String
   
    Public Property gadgets() As String
        Get
            Return Me.gadgetsField
        End Get
        Set(value As String)
            Me.gadgetsField = value
        End Set
    End Property
End Class

 Public Class catalogNovel
    Private priceField As Integer
   
    Public Property price() As Integer
        Get
            Return Me.priceField
        End Get
        Set(value As Integer)
            Me.priceField = value
        End Set
    End Property
End Class

I am getting error "Index was outside the bounds of the array.

How to get both prices.

Thanks in advance.

Deserialize -> Serialize produces invalid XML file

$
0
0

Hi,

I'm trying to read and write .gpx file produced by an Garmin handheld device. Everything is working fine except the output file is invalid according to http://www.validome.org/xml/validate/ -validator.

Even if I just read the file into a dataset and write it immediately to another file without making any changes to data, I get invalid output. Data itself is valid but something gets wrong with header (schema definitions etc.)

Public Sub TryXmlDocument()
     Dim xmlFile As XmlReader
     Dim ds as New DataSet
     xmlFile = XmlReader.Create("filename.gpx", New XmlReaderSettings())
     ds.ReadXml(xmlFile, XmlReadMode.Auto)
     ds.WriteXml("filename_new.gpx")
End Sub

Anyone out there with solution?

XML Advanced Electronic Signatures (XAdES)

$
0
0

I am making vb.net 2005 application for creating and verifying digital signatures over any document.

It has to be XAdES signature, not XMLDSIG.

I can't find any support for XAdES signatures in VS 2005, althought there is a very good support  XMLDSIG!

Does anybody know if there is any (posible Microsoft) dll that supports XAdES signatures?

I found .ppt file  made by Eddy Rubens (Microsoft Services Belgium) that was used on a presentation for presenting Microsoft.Xades.dll. Presentation was dated 24/06/2004, but can not find any new information about this dll.

Is the production stopped? If yes, why?

Is there ever going to be support for XAdES?

How can I ask anybody from Microsoft team about this?

Dynamic xml Serialization

$
0
0

I am trying to generate an xml by serializing and facing some issues. Thereis a part of xml which is dynamic. the section "person" is dynamic i.e the sub sections
(name and age)under person can increase or decrease. I am able to serialie the class with static value( with single person name and age) but when getting multiple 
values then I am not able to handle that.All the values are fetched from database and every name and age is store as a distinct row in database.So if I have 2 names and age then it will be stored
as 2 distinct rows in database. I tried to create a loop(on basis of number of rows) but not able understand how to incorporate the dynamic section to rest of xml part.

Can someone help on this?

create table persondetails(name varchar(20),age int)
insert into persondetails(name,age)
select 'Dann',21
union all
select 'Scott',23
union all
Select 'Allen',24

Desired output XML:

<details>
 <description>Some description</description>
 <hobby> Anything</hobby>

<person>
   <name>Dann</name>
   <age>21</age>
   <name>Scott</name>
   <age>23</name>
</person>

</details>

   
Viewing all 935 articles
Browse latest View live


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