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

allowing an int to take a null value

$
0
0

I am really stuck with this and don't want to take the easy way out an just make the type string:

Google ended up showing me this but I did not find it anywhere in the schema rules and it did not work.

<xs:element minOccurs="0" name="myNumber"  nillable="true" type="xs:int"/>

If I have a null I want it to show zero........am I really going to have to use the string type?

It is a child element and I would rather just fail its parent then fail all the parents (the whole xml doc).



Use Windows environment variables with xml file

$
0
0

Hi,

Is there a way to use an environment variable like %username%, into a xml file? I need to create a scheduled task from .xml file but I need to get the current logged user into the .xml file.

I'll appreciate any suggestion.

Regards.

<?xml version="1.0" encoding="UTF-16"?><Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><RegistrationInfo><Date>2015-02-06T07:38:03</Date><Author>NEEDLOGGEDUSERHERE</Author></RegistrationInfo><Triggers><CalendarTrigger><StartBoundary>2015-02-06T07:45:00</StartBoundary><Enabled>true</Enabled><ScheduleByWeek><DaysOfWeek><Friday /></DaysOfWeek><WeeksInterval>1</WeeksInterval></ScheduleByWeek></CalendarTrigger><CalendarTrigger><StartBoundary>2015-02-06T19:30:00</StartBoundary><Enabled>true</Enabled><ScheduleByWeek><DaysOfWeek><Friday /></DaysOfWeek><WeeksInterval>1</WeeksInterval></ScheduleByWeek></CalendarTrigger><CalendarTrigger><StartBoundary>2015-02-06T02:00:00</StartBoundary><Enabled>true</Enabled><ScheduleByWeek><DaysOfWeek><Friday /></DaysOfWeek><WeeksInterval>1</WeeksInterval></ScheduleByWeek></CalendarTrigger></Triggers><Principals><Principal id="Author"><UserId>NEEDLOGGEDUSERHERE</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>true</StopIfGoingOnBatteries><AllowHardTerminate>true</AllowHardTerminate><StartWhenAvailable>false</StartWhenAvailable><RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable><IdleSettings><StopOnIdleEnd>true</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings><AllowStartOnDemand>true</AllowStartOnDemand><Enabled>true</Enabled><Hidden>false</Hidden><RunOnlyIfIdle>false</RunOnlyIfIdle><WakeToRun>false</WakeToRun><ExecutionTimeLimit>P3D</ExecutionTimeLimit><Priority>7</Priority></Settings><Actions Context="Author"><Exec><Command>\\apptorun\app.exe</Command></Exec></Actions></Task>

Serialize XML from Object (need to create: type and ![CDATA[)

$
0
0

How can i create a line like this:

<ATTRIBUTE type="Size"><![CDATA["One Size"]]></ATTRIBUTE>

I dont know how create the type and CData. Currently I have the following classes:

public class ATTRIBUTES
        {
            public ATTRIBUTE ATTRIBUTE;
        }

        public class ATTRIBUTE
        {
            public string ATTR { get; set; }
        }
I need to end up with something like the following.

<ATTRIBUTES><ATTRIBUTE type="Colour"><![CDATA["Black"]]></ATTRIBUTE><ATTRIBUTE type="Size"><![CDATA["One Size"]]></ATTRIBUTE></ATTRIBUTES>

Thanks

I am having a problem finding a child node (c#)

$
0
0

Hi !

My XML is a bit like this:

<Layers><Layer><OverlapNames>
       ...</OverlapNames><CommonNames>
       ...</CommonNames><SnapNames><SnapName Name="zzz" /><SnapName Name="yyy" /></SnapNames</Layer></Layers>

I have this initial XmlNode which returns a valid object:

XmlNode nodeLayer = xmlDoc.SelectSingleNode(String.Format("Layers/Layer[@Name=\"{0}\"]", strLayer));

Now what I want to do is try to find within this node if there is a SnapNames/SnapName with a value of, eg: zzz.

So I thought this would work (where strLayer2 is "zzz":

XmlNode nodeLayer2 = nodeLayer.SelectSingleNode(String.Format(".//SnapsNames/SnapName[@Name=\"{0}\"]", strLayer2));

// Also tried:
XmlNode nodeLayer2 = nodeLayer.SelectSingleNode(String.Format("SnapsNames/SnapName[@Name=\"{0}\"]", strLayer2));


But nodeLayer2 is always null! The only way I have managed to do it so far is like this:

bool bIsSnapName = false;
if (nodeLayer.HasChildNodes)
{
  for (int i=0; i<nodeLayer.ChildNodes.Count; i++)
  {
      if (nodeLayer.ChildNodes[i].Name == "SnapNames")
      {
           XmlNode nodeSnapNames = nodeLayer.ChildNodes[i];
           XmlNode nodeSnapName = nodeSnapNames.SelectSingleNode(String.Format("SnapName[@Name=\"{0}\"]", strLayer2));
           if (nodeSnapName != null)
           {
              bIsSnapName = true;
              break;
           }
      }
  }
}

What am I doing wrong? How can I take the nodeLayer object and return the sub node from SnapNames/SnapName where Name = "zzz"?

Thanks.

XML Schema Compilation Error for Valid XML Schema?

$
0
0

I am working with the following XML schema:

<?xml version="1.0" encoding="utf-8"?><xs:schema
	targetNamespace="http://tempuri.org/XMLSchema.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:uk-gcd="http://www.companieshouse.gov.uk/ef/xbrl/uk/fr/gaap/ae/2009-06-21"><xs:import
	schemaLocation="http://resources.companieshouse.gov.uk/ef/xbrl/uk/fr/gaap/ae/2009-06-21/uk-gaap-ae-2009-06-21.xsd"
	namespace="http://www.companieshouse.gov.uk/ef/xbrl/uk/fr/gaap/ae/2009-06-21"
	/><xs:element
		id="uk-gaap-ae_NameAccountants"
		type="uk-gcd:nonEmptyStringItemType"
		name="NameAccountants"
		nillable="true"
	/></xs:schema>

When I load this schema in Visual Studio 2013's XML Schema Explorer, I can see the uk-gaap-ae_NameAccountants element and its type, which is the nonEmptyStringItemType found in the uk-gcd namespace. All is well.

However, I run into problems when I try to compile the schema within code:

var schemaReader = System.Xml.XmlTextReader.Create("my.xsd");
var thisSchema = System.Xml.Schema.XmlSchema.Read(schemaReader, null);
var thisSchemaSet = new System.Xml.Schema.XmlSchemaSet();
thisSchemaSet.Add(thisSchema);
thisSchemaSet.Compile();

The compilation call throws an XmlSchemaException:

System.Xml.Schema.XmlSchemaException was unhandled by user code
  HResult=-2146231999
  Message=Type 'http://www.companieshouse.gov.uk/ef/xbrl/uk/fr/gaap/ae/2009-06-21:nonEmptyStringItemType' is not declared.
  Source=System.Xml
  LineNumber=14
  LinePosition=3
  SourceUri=file:///C:/Users/jferguso/Desktop/WorkItem10871.xsd
  StackTrace:
       at System.Xml.Schema.XmlSchemaSet.InternalValidationCallback(Object sender, ValidationEventArgs e)
       at System.Xml.Schema.BaseProcessor.SendValidationEvent(XmlSchemaException e, XmlSeverityType severity)
       at System.Xml.Schema.Compiler.CompileElement(XmlSchemaElement xe)
       at System.Xml.Schema.Compiler.Compile()
       at System.Xml.Schema.Compiler.Execute(XmlSchemaSet schemaSet, SchemaInfo schemaCompiledInfo)
       at System.Xml.Schema.XmlSchemaSet.Compile()
       at JeffFerguson.Test.Gepsio.WorkItemsTests.WorkItem10871Test() in c:\Users\JFergu99\Source\Workspaces\gepsio\JeffFerguson.Test.Gepsio\WorkItemsTests.cs:line 108
  InnerException:

Why does the type appear correctly in Visual Studio but cannot be found during compilation?

How to debug XmlDocument validation code from within Visual Studio

$
0
0
While within Visual Studio 2012 I do not get any exceptions triggered for validation errors from the XmlDocument.Validate method.  I used the example code at Microsoft's site for XmlDocument.Validate ( XmlDocument.Validate method -   https://msdn.microsoft.com/en-us/library/ms162371(v=vs.110).aspx ) and I get this behavior.  However, when I execute the compiled code from the command prompt it behaves as expected - that is, it displays appropriate validation failure messages from the exception handler.  How can I "configure" Visual Studio debugger to allow validation to work?


XElement Save Adds Leading Charachters

$
0
0

Dear Experts,

XElement objEl = XElement.Load(Filename);
            objEl = objEl.Element("ACES");
            XNamespace xsi = XNamespace.Get(@"http://www.w3.org/2001/XMLSchema-instance");
            XNamespace aces = XNamespace.Get(@"ACES_DLR.xsd");
            objEl.SetAttributeValue(XNamespace.Xmlns + "xsi", xsi);
            objEl.Add(new XAttribute(xsi + "noNamespaceSchemaLocation", aces));
            objEl.Save(Filename);
after the file is saved the saved file have these 3 characters ∩╗┐ , ascii vales[239,187,191]  how to suppress this 3 charachteres while write and   can you explain why they get added and what is there purpose

XSD schema to xml file generation using C#

$
0
0

Hi fellow developers,

I need small help with my current scenario.

I have 2 xsd schemas one is input and other is output.

Now my requirement is based on those xsd template or structure, i need to write a C# code that takes the 1 xsd template as input in xml format and then do some mapping and then set that values to 2 xsd template in xml format.

Can you please guide or assist in this regards ??

It would be helpful if we have the flexibility of configuring the schema properties.


XmlSchemaSet vs XmlSchema - Browsing all xsds while using xsd:import

$
0
0

Hello all 

I have a parent XSD with multiple xsd:import. I am trying to import all the elements from the parent XSD using my utility and there is a difference of "schema.Elements.Count" between C# code in .NET1.1 and .NET4.0

.NET1.1 code snippet

 XmlSchema schema;

xmlReader = new XmlTextReader(sourceUri);
xmlReader.Read();
encoding = xmlReader.Encoding;
schema = XmlSchema.Read(xmlReader, validationHandler);
schema.Compile(validationHandler);

.NET4 code snippet

 XmlSchema schema;

xmlReader = new XmlTextReader(sourceUri);
xmlReader.Read();
encoding = xmlReader.Encoding;

schema = XmlSchema.Read(xmlReader, validationHandler);
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.ValidationEventHandler += new ValidationEventHandler(validationHandler);
schemaSet.Add(schema);

schemaSet.Compile()

My questions

1) I am trying to browse the schemas and display the nodes and its elements, attributes etc.

Parent xsd has 3 elements and the xsd which was imported has 1 element. In  .NET4 the "schema.Elements.Count" gives only 3 whereas the .NET1.1 gives 4 . Due to this I am unable to display all 4 nodes ( to be more clear it displays the nodes from parent xsd but not from imported xsd) in .NET4 where as I am able to display all 4 nodes in .NET1.1

I have a huge xsd which cannot be shared with 72 nodes. I can upload the simple testcase where I could reproduce the issue with my utility.

Thanks in advance

Sateesh


MSXML2::IXSLProcessor transform() Fails

$
0
0

The call to transform HResult returns Unspecified error.

The same code and xml/xsl files have been tried on different Windows 7 machines. Some work and others do not.

Does anyone know why this would work on some machines where on others it does not even though the code and files used are identical?

Have checked version of msxml3.dll and they are the same on all the machines.

This is running on Windows 7, 64 bit, SP1.

Thanks in adavnce for any help

XData: Schematized Data Exchange Solution

$
0
0

Hi, I'd like to introduce XData to those who are not satisfied with XML/XML Schema :)

The world needs to exchange data. Data needs to have a specification. Schema is the specification of the data. We the programmers need to program everything. XData is a programming-friendly solution for schematized data. This is the reason XData comes to birth.

XData is an open source project, its website is https://github.com/knat/XData.

XData Tutorial: EBusiness Web Application Simulation.

Modelling XSD with multiple namespaces in SOM

$
0
0

Hi Guys,

I am building an application that extracts Types and there namespace from XSD files. 

The XSD file could be complex with multiple imports and multiple namespaces declared within. Here is simple example...

<schema targetNamespace="http://www.example.com/Report" xmlns="http://www.w3.org/2001/XMLSchema"

xmlns:r="http://www.example.com/Report" xmlns:xipo="http://www.example.com/IPO" elementFormDefault="qualified"><import namespace="http://www.example.com/IPO" schemaLocation="ipo.xsd"/><complexType name="PartsType"><sequence><element name="part" maxOccurs="unbounded"><complexType><simpleContent><extension base="string"><attribute name="number" type="xipo:SKU"/></extension></simpleContent></complexType></element></sequence></complexType></schema>

When I load this schema into a schema cache and traverse the tree I am missing the namespace of the imported type and the prefix has been stripped from its name.

<xsd:complexType name='PartsType'><xsd:sequence><xsd:element name='part' maxOccurs='unbounded'  abstract='False'id=''namespace='http://www.example.com/Report'><xsd:complexType><xsd:attribute name='number' type='SKU' namespace='' use='optional'/></xsd:complexType></xsd:element></xsd:sequence></xsd:complexType>

So originally the type was "xipo:SKU" which has now become "SKU".

The namespace should be "http://www.example.com/IPO"which is the namespace for the prefix "xipo".

Any suggestions on how to preserve the namespaces in complex XSD's like this?  Is the SOM model appropriate for this application?

Any help would be much appreciated.

Daniel

XmlReader with encoding fallback

$
0
0
Hello,
I need to create a XmlReader for a stream with encoding detected from the stream and, if it cannot be detected or if it is detected as UTF-8, use UTF-8 that does not throw on invalid characters.

What are my options - do I need to manually detect the encoding first, pass it using XmlReaderContext after removing the preambles myself? Sounds like there should be an easier way...

Thanks,
Jan

Using LINQ to extract list from XML [OpenXML]

$
0
0

The following is the XML file that is generated from Word document through OpenXML:

XML Link here

I want to get the following list using LINQ:


How to prohibit leading and traling whitespace in XML Schema

$
0
0
I want to prohibit the use of leading and trailing whitespace in an element but besides that all other content is allowed.

For examble <   word? > should give a validation error.

I do not want to use

<whiteSpace value="collapse"/>

Because it doesn't give a validation error.

Is it possible to make a pattern og in some other way solve my problem?

Thanks in advance, Martin

Validate XML against XSD with imported xsd's

$
0
0

Hello,

I'm stuck for a while attempting to validate a xml against some xsd's. In the code below you can find my xsd's structure: (I need to use this structure in order to reuse the baseXsd's files.

CommonTypes.xsd

<?xml version="1.0" encoding="utf-8"?><xs:schema id="CommonTypes" targetNamespace="http://test.com/CommonTypes"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    attributeFormDefault="qualified"><xs:simpleType name="NonEmptyString"><xs:restriction base="xs:string"><xs:minLength value="1"/></xs:restriction></xs:simpleType></xs:schema>

CommonLog.xsd

<?xml version="1.0" encoding="utf-8"?><xs:schema id="CommonLogConfig"
    targetNamespace="http://test.com/CommonLogConfig"
    xmlns:cmn="http://test.com/CommonTypes"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    attributeFormDefault="qualified"><xs:import schemaLocation="..\Base\CommonTypes.xsd" namespace="http://test.com/CommonTypes" /><xs:simpleType name="LogName"><xs:restriction base="xs:string"/></xs:simpleType><xs:simpleType name="LogPath"><xs:restriction base="cmn:NonEmptyString"/></xs:simpleType></xs:schema>

LogConfig.xsd

<?xml version="1.0" encoding="utf-8"?><xs:schema xmlns:mlc="http://test.com/CommonLogConfig"
           targetNamespace="component1_LogConfig"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified"
           attributeFormDefault="qualified"><xs:import schemaLocation="..\Base\CommonLogConfig.xsd" namespace="http://test.com/CommonLogConfig" /><xs:element name="root"><xs:complexType><xs:sequence><xs:element name="default"><xs:complexType><xs:all><xs:element name="LogName" type="mlc:LogName" fixed="component.name" /><xs:element name="LogPath" type="mlc:LogPath"/></xs:all></xs:complexType></xs:element></xs:sequence></xs:complexType></xs:element></xs:schema>

LogConfig.xml

<?xml version="1.0" encoding="utf-8"?><root xmlns="component1_LogConfig"><default><LogName>component.name</LogName><LogPath></LogPath></default></root>

As you can probably notice, the <LogPath> key on the LogConfig is empty, but, it is defined as a NonEmptyString type. That is the way I'm validating the xml against xsd:

FileStream stream = new FileStream("LogConfig.xml", FileMode.Open);
XmlValidatingReader vr = new XmlValidatingReader(stream, XmlNodeType.Element, null);

vr.Schemas.Add(null, "LogConfig.xsd");
vr.ValidationType = ValidationType.Schema;
vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

while (vr.Read()) ;

The validationCallBack is not being fired.

I suppose it is possible since the visual studio show me the error at compile time:

Schema Validation Questions

$
0
0

I'm not really sure if this is the proper forum, so please advise if I got that wrong.

I'm quite the newbie on schema validations, but have had some success using them.  In the past, I've used tools such as XRay and Editix to do this.  Now I'm experimenting with doing this in my c# project using the XmlSchemaSet.

One thing I have noticed, regardless of which tool being used, is that if namespaces don't match, the validation seems to give a "false positive", as it reports successful validation even if there are missing nodes as per the schema.

It seems like if the namespaces don't match, the validation should either fail and advise of that, or ignore the namespaces and use the schema to simply validate against the xml being supplied.  It is misleading to report a successful validation just because the namespaces don't match.

Am I totally misunderstanding this topic?  Are there any articles you can recommend to learn this stuff?

Thanks for any help...


Ron Mittelman

C# transformation script included within XSLT stylesheet doesn’t work in IE11

$
0
0

Contrary to these articles:

https://msdn.microsoft.com/en-us/library/vstudio/533texsx(v=vs.100).aspx

http://docs.composite.net/FAQ/Developer?q=How+to+run+CSharp+function+in+XSLT%3f

As soon as I include the following:

<msxsl:script language="C#" implements-prefix="user">

</msxsl:script>

into the XSLT stylesheet the output of this XML:

<member name="M:MyNamespace.Connect(System.Object[])">

           <summary>

           Opens connection to the database

           </summary>

           <param name="parameters">Array of connection parameters</param>

           <returns>True is successfully connected, false otherwise.</returns>

  </member>

will look like this:

M:MyNamespace.Connect(System.Object[])Opens connection to the database Array of connection True is successfully connected, false otherwise.

when opened in Internet Explorer 11. On the other hand when the same XML + XSLT is opened in Visual Studio 2013 the output looks correct. Replacing “language="C#"” with “language="javascript"” corrects the output in IE.

Any ideas, please?

Thank you,

Eugene

Is there a way to modify the style sheet so that it transforms an XML document with empty tags as ?

$
0
0

I have extracted some code from codeproject to reindent an XML document. Does anyone know how I can modify the stylesheet to make it so that the transform of an XML file will result in empty tags showing up as <tag /> instead of <tag></tag>?

// http://www.codeproject.com/Articles/43309/How-to-create-a-simple-XML-file-using-MSXML-in-C
MSXML2::IXMLDOMDocumentPtr FormatDOMDocument(MSXML2::IXMLDOMDocumentPtr pDoc)
{
    LPCSTR const static szStyleSheet =
        R"!(<?xml version="1.0" encoding="utf-8"?>)!"
        R"!(<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">)!"
        R"!(    <xsl:output method="xml" indent="yes"/>)!"
        R"!(    <xsl:template match="@* | node()">)!"
        R"!(        <xsl:copy>)!"
        R"!(            <xsl:apply-templates select="@* | node()"/>)!"
        R"!(        </xsl:copy>)!"
        R"!(    </xsl:template>)!"
        R"!(</xsl:stylesheet>)!";

    MSXML2::IXMLDOMDocumentPtr pXmlStyleSheet;
    pXmlStyleSheet.CreateInstance(__uuidof(MSXML2::DOMDocument60));
    pXmlStyleSheet->loadXML(szStyleSheet);

    MSXML2::IXMLDOMDocumentPtr pXmlFormattedDoc;
    pXmlFormattedDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60));

    CComPtr<IDispatch> pDispatch;
    HRESULT hr = pXmlFormattedDoc->QueryInterface(IID_IDispatch, (void**)&pDispatch);
    if (SUCCEEDED(hr))
    {
        _variant_t    vtOutObject;
        vtOutObject.vt = VT_DISPATCH;
        vtOutObject.pdispVal = pDispatch;
        vtOutObject.pdispVal->AddRef();

        hr = pDoc->transformNodeToObject(pXmlStyleSheet, vtOutObject);
    }

    //By default it is writing the encoding = UTF-16. Let us change the encoding to UTF-8

    // <?xml version="1.0" encoding="UTF-8"?>
    MSXML2::IXMLDOMNodePtr pXMLFirstChild = pXmlFormattedDoc->GetfirstChild();
    // A map of the a attributes (vesrsion, encoding) values (1.0, UTF-8) pair
    MSXML2::IXMLDOMNamedNodeMapPtr pXMLAttributeMap =  pXMLFirstChild->Getattributes();
    MSXML2::IXMLDOMNodePtr pXMLEncodNode = pXMLAttributeMap->getNamedItem(_T("encoding"));
    pXMLEncodNode->PutnodeValue(_T("UTF-8"));    //encoding = UTF-8

    return pXmlFormattedDoc;
}

Or, if there is some other method for reindenting a MSXML2::IXMLDOMDocumentPtr object where I can specify how I want empty tags to be stored, that would be great too.  However, I don't want it to lose its status of an MSXML2::IXMLDOMDocumentPtr object. I.e. I would like to still perform operations on the result as if it was still an MSXML2::IXMLDOMDocumentPtr object.

Thanks,

A


Adrian




XML Schema validator fails to load XML Schema from URL

$
0
0

I'm trying to validate an XML document against a set of XML Schemas and the parser seems to freak out: even though all the schemas are referred to in the XML and are properly recognized by Schemas field in XML document properties, I get warnings (multiple instances):

Request for the permission of type 'System.Net.WebPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed
Cannot resolve the 'schemaLocation' attribute

The schema referenced from this location in your document contains errors

The warning locations are also seemingly random - errors in schema locations are reported on closing tags inside XML or on whitespaces, and so on.

The first warning (System.Net.WebPermission) suggests it has something to do with access to remote schemas, but all the necessary remote schemas are visible in XML Schema Set editor for the document. I also enabled downloading of XML schemas in XML text editor options.

Viewing all 935 articles
Browse latest View live


Latest Images

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