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

Replace Bookmars looses formatting in Word 2010

$
0
0

Hello

i'm replacing bookmark in a word 2010 file but it loses formatting (like indentation, numbering, lists etc)

Maybe i'm doing wrong in my code.

This is the code of function i use to replace bookmark :

        public static void ReplaceBookmarkText(WordprocessingDocument doc, string bookmarkName, string replacementText)
        {
            XDocument xDoc = doc.MainDocumentPart.GetXDocument();

            XElement bookmark = xDoc.Descendants(W.bookmarkStart).FirstOrDefault(d => (string)d.Attribute(W.name) == bookmarkName);

            if (bookmark == null)
                throw new BookmarkReplacerException("Document doesn't contain bookmark.");

            if (bookmark.Parent.Name.Namespace == M.m)
                throw new BookmarkReplacerException("Replacing text in math formulas is not supported.");

            if (OpenXmlPowerTools.RevisionAccepter.HasTrackedRevisions(doc))
                throw new BookmarkReplacerException("Replacing bookmark text in documents that have tracked revisions is not supported.");

            if (xDoc.Descendants(W.sdt).Any())
                throw new BookmarkReplacerException("Replacing bookmark text in documents that have content controls is not supported.");

            XElement newRoot = (XElement)FlattenParagraphsTransform(xDoc.Root);

            XElement startBookmarkElement = newRoot.Descendants(W.bookmarkStart).Where(d => (string)d.Attribute(W.name) == bookmarkName).FirstOrDefault();

            int bookmarkId = (int)startBookmarkElement.Attribute(W.id);

            XElement endBookmarkElement = newRoot.Descendants(W.bookmarkEnd).Where(d => (int)d.Attribute(W.id) == bookmarkId).FirstOrDefault();

            if (startBookmarkElement.Ancestors(W.hyperlink).Any() || endBookmarkElement.Ancestors(W.hyperlink).Any())
                throw new BookmarkReplacerException("Bookmark is within a hyperlink.  Can't replace text.");

            if (startBookmarkElement.Ancestors(W.fldSimple).Any() || endBookmarkElement.Ancestors(W.fldSimple).Any())
                throw new BookmarkReplacerException("Bookmark is within a simple field.  Can't replace text.");

            if (startBookmarkElement.Ancestors(W.smartTag).Any() || endBookmarkElement.Ancestors(W.smartTag).Any())
                throw new BookmarkReplacerException("Bookmark is within a smart tag.  Can't replace text.");

            if (startBookmarkElement.Parent != endBookmarkElement.Parent)
                throw new BookmarkReplacerException("Bookmark start and end not at same levels.  Can't replace text.");

            XElement parentElement = startBookmarkElement.Parent;

            var elementsBetweenBookmarks = startBookmarkElement.ElementsAfterSelf().TakeWhile(e => e != endBookmarkElement);

            var newElements = parentElement.Elements().TakeWhile(e => e != startBookmarkElement)
                .Concat(new[]
                {
                    startBookmarkElement,
                    new XElement(BookmarkReplacerCustomNamespace + "Insert",
                        elementsBetweenBookmarks
                            .Where(e => e.Name == W.r)
                            .Take(1)
                            .Elements(W.rPr)
                            .FirstOrDefault()),
                })
                .Concat(elementsBetweenBookmarks.Where(e => e.Name != W.p &&
                    e.Name != W.r && e.Name != W.tbl))
                .Concat(new[]
                {
                    endBookmarkElement
                })
                .Concat(endBookmarkElement.ElementsAfterSelf());

            parentElement.ReplaceNodes(newElements);

            newRoot = (XElement)UnflattenParagraphsTransform(newRoot);
            newRoot = (XElement)ReplaceInsertElement(newRoot, replacementText);
            newRoot = (XElement)DemoteRunChildrenOfBodyTransform(newRoot);

            xDoc.Elements().First().ReplaceWith(newRoot);

            doc.MainDocumentPart.PutXDocument();
        }


Problem using XmlTextWriter export to excel

$
0
0

Hi everybody,

   Having problem getting the desired result of xml file. Can you guys help me with this? The function is exporting data from database to an excel file, and then importing the changes in
data back to database. Thanks in advanced.


Current Code:
[code]

const string sheet = "urn:schemas-microsoft-com:office:spreadsheet", office = "urn:schemas-microsoft-com:office:office", excel = "urn:schemas-microsoft-com:office:excel";
     XmlTextWriter xmlTextWriter = new XmlTextWriter(filePath, System.Text.Encoding.Default);
     xmlTextWriter.Formatting = Formatting.Indented;
     xmlTextWriter.WriteStartDocument();
     xmlTextWriter.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");
     xmlTextWriter.WriteStartElement(string.Empty, "Workbook", sheet);
     xmlTextWriter.WriteAttributeString("xmlns", "o", "http://www.w3.org/2000/xmlns/", office);
     xmlTextWriter.WriteAttributeString("xmlns", "x", "http://www.w3.org/2000/xmlns/", excel);

     xmlTextWriter.WriteStartElement(string.Empty, "DocumentProperties", office);
     xmlTextWriter.WriteElementString("Author", "Somebody");
     xmlTextWriter.WriteEndElement();//End DocumentProperties

     xmlTextWriter.WriteStartElement(string.Empty, "ExcelWorkbook", excel);     
     xmlTextWriter.WriteElementString("WindowHeight", "10230");
     xmlTextWriter.WriteElementString("WindowWidth", "13275");
     xmlTextWriter.WriteElementString("WindowTopX", "480");
     xmlTextWriter.WriteElementString("WindowTopY", "75");
     xmlTextWriter.WriteElementString("ProtectStructure", "False");
     xmlTextWriter.WriteElementString("ProtectWindows", "False");
     xmlTextWriter.WriteEndElement();//End ExcelWorkbook

     xmlTextWriter.WriteStartElement("Styles", sheet);
     xmlTextWriter.WriteStartElement(string.Empty, "Style", sheet);
     xmlTextWriter.WriteAttributeString("ID", sheet, "Default");
     xmlTextWriter.WriteAttributeString("Name", "ss", "Normal");
     xmlTextWriter.WriteStartElement("Alignment", sheet);     
     xmlTextWriter.WriteAttributeString("Vertical", "ss", "Bottom");
     xmlTextWriter.WriteEndElement();//End Alignment
     xmlTextWriter.WriteStartElement("Font", sheet);
     xmlTextWriter.WriteEndElement();//End Font
     xmlTextWriter.WriteStartElement("Interior", sheet);
     xmlTextWriter.WriteEndElement();//End Interior
     xmlTextWriter.WriteStartElement("NumberFormat", sheet);
     xmlTextWriter.WriteEndElement();//End NumberFormat
     xmlTextWriter.WriteStartElement("Protection", sheet);
     xmlTextWriter.WriteEndElement();//End Protection    
     xmlTextWriter.WriteEndElement();//End Style
     xmlTextWriter.WriteEndElement();//End Styles

     xmlTextWriter.WriteStartElement(string.Empty,"WorkSheet", sheet);
     xmlTextWriter.WriteAttributeString(string.Empty,"Name", sheet, "Sheet1");

     xmlTextWriter.WriteStartElement(string.Empty, "Table", sheet);
     xmlTextWriter.WriteAttributeString("ExpandedColumnCount", "1");
     xmlTextWriter.WriteAttributeString("ExpandedRowcount", "1");
     xmlTextWriter.WriteAttributeString("TotalColumns", "3");
     xmlTextWriter.WriteAttributeString("TotalRows", "1");//To be modified

     //xmlTextWriter.WriteStartElement(string.Empty, "Column", sheet);
     //xmlTextWriter.WriteAttributeString("ss", "Index", sheet, "1");
     //xmlTextWriter.WriteAttributeString("ss", "AutoFitWidth", sheet, "0");
     //xmlTextWriter.WriteAttributeString("ss", "Width", sheet, "82.5");
     //xmlTextWriter.WriteEndElement();//End Column    

     xmlTextWriter.WriteStartElement("Row", sheet);
     
     xmlTextWriter.WriteStartElement("Cell", sheet);
     //xmlTextWriter.WriteStartElement(string.Empty, "Data", sheet);     
     //xmlTextWriter.WriteElementString("Data","ID");
     xmlTextWriter.WriteRaw("<Data ss:Type=\"String\">ID</Data>");
     //xmlTextWriter.WriteAttributeString("ss", "Type", sheet, "String");
     //xmlTextWriter.WriteEndElement();//End Data    
     xmlTextWriter.WriteEndElement();//End Cell 

     xmlTextWriter.WriteStartElement("Cell", sheet);
     //xmlTextWriter.WriteStartElement(string.Empty, "Data", sheet);
     //xmlTextWriter.WriteElementString("Data", "Name");
     xmlTextWriter.WriteRaw("<Data ss:Type=\"String\">Name</Data>");
     //xmlTextWriter.WriteAttributeString("ss", "Type", sheet, "String");
     //xmlTextWriter.WriteEndElement();//End Data    
     xmlTextWriter.WriteEndElement();//End Cell   

     xmlTextWriter.WriteEndElement();//End Row    

     xmlTextWriter.WriteStartElement("Row", sheet);
     xmlTextWriter.WriteStartElement("Cell", sheet);
     //xmlTextWriter.WriteStartElement(string.Empty, "Data", sheet);
     //xmlTextWriter.WriteElementString(string.Empty, "Data", excel, "1");
     xmlTextWriter.WriteRaw("<Data ss:Type=\"Number\">1</Data>");
     //xmlTextWriter.WriteAttributeString("ss", "Type", sheet, "Number");
     //xmlTextWriter.WriteEndElement();//End Data    
     xmlTextWriter.WriteEndElement();//End Cell 
     xmlTextWriter.WriteStartElement("Cell", sheet);
     //xmlTextWriter.WriteStartElement(string.Empty, "Data", sheet);
     //xmlTextWriter.WriteElementString(string.Empty, "Data", excel, "Sample");
     xmlTextWriter.WriteRaw("<Data ss:Type=\"String\">Sample</Data>");
     //xmlTextWriter.WriteAttributeString("ss", "Type", sheet, "String");
     //xmlTextWriter.WriteEndElement();//End Data    
     xmlTextWriter.WriteEndElement();//End Cell   
     xmlTextWriter.WriteEndElement();//End Row    

 

     xmlTextWriter.WriteEndElement();//End Table    

     xmlTextWriter.WriteStartElement(string.Empty, "WorksheetOptions", excel);
     xmlTextWriter.WriteStartElement("Selected", excel);
     xmlTextWriter.WriteEndElement();//End Selected    
     xmlTextWriter.WriteStartElement("Panes", excel);
     xmlTextWriter.WriteStartElement("Pane", excel);     
     xmlTextWriter.WriteElementString("Number", "3");//To be modified
     xmlTextWriter.WriteElementString("ActiveRow", "3");//To be modified
     xmlTextWriter.WriteElementString("ActiveCol", "3");//To be modified

     xmlTextWriter.WriteEndElement();//End Pane    
     xmlTextWriter.WriteEndElement();//End Panes    
     xmlTextWriter.WriteElementString("ProtectObjects", "False");//To be modified
     xmlTextWriter.WriteElementString("ProtectScenarios", "False");//To be modified
     xmlTextWriter.WriteEndElement();//End WorksheetOptions    
     xmlTextWriter.WriteEndElement();//End WorkSheet 
     xmlTextWriter.WriteEndElement();//End Workbook

     xmlTextWriter.WriteEndDocument();
     xmlTextWriter.Close();
[code]

 

Desired XML Result:

<?xml version="1.0"?>
<?mso-application progid='Excel.Sheet'?>
<Workbook xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"> 
<Worksheet ss:Name="Sheet1">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Version>11.8107</Version>
 </DocumentProperties>
 <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
  <WindowHeight>10005</WindowHeight>
  <WindowWidth>10005</WindowWidth>
  <WindowTopX>120</WindowTopX>
  <WindowTopY>135</WindowTopY>
  <ProtectStructure>False</ProtectStructure>
  <ProtectWindows>False</ProtectWindows>
 </ExcelWorkbook>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
 </Styles>
  <Table ss:ExpandedColumnCount="4" ss:ExpandedRowCount="4" x:FullColumns="1"
   x:FullRows="1">
   <Column ss:Index="3" ss:AutoFitWidth="0" ss:Width="82.5"/>
   <Row>
    <Cell><Data ss:Type="String">ID</Data></Cell>
    <Cell><Data ss:Type="String">Name</Data></Cell>
    <Cell><Data ss:Type="String">Name in Chinese</Data></Cell>
    <Cell><Data ss:Type="String">Name in Chinese</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="Number">1</Data></Cell>
    <Cell><Data ss:Type="String">gg</Data></Cell>
    <Cell ss:Index="4"><Data ss:Type="Boolean">1</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="Number">2</Data></Cell>
    <Cell><Data ss:Type="String">ss</Data></Cell>
    <Cell><Data ss:Type="String">s</Data></Cell>
    <Cell><Data ss:Type="Boolean">0</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="Number">3</Data></Cell>
    <Cell><Data ss:Type="String">ss</Data></Cell>
    <Cell><Data ss:Type="String">s</Data></Cell>
   </Row>
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <Selected/>
   <Panes>
    <Pane>
     <Number>3</Number>
     <ActiveRow>3</ActiveRow>
     <ActiveCol>6</ActiveCol>
    </Pane>
   </Panes>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions> 
 </Worksheet>
</Workbook>


Actual XML File Result:

<?xml version="1.0" encoding="Windows-1252"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="urn:schemas-microsoft-com:office:spreadsheet">
  <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
    <Author>Somebody</Author>
  </DocumentProperties>
  <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
    <WindowHeight>10230</WindowHeight>
    <WindowWidth>13275</WindowWidth>
    <WindowTopX>480</WindowTopX>
    <WindowTopY>75</WindowTopY>
    <ProtectStructure>False</ProtectStructure>
    <ProtectWindows>False</ProtectWindows>
  </ExcelWorkbook>
  <Styles>
    <Style d3p1:ID="Default" d3p2:Name="Normal" xmlns:d3p2="ss" xmlns:d3p1="urn:schemas-microsoft-com:office:spreadsheet">
      <d3p1:Alignment d3p2:Vertical="Bottom" />
      <d3p1:Font />
      <d3p1:Interior />
      <d3p1:NumberFormat />
      <d3p1:Protection />
    </Style>
  </Styles>
  <WorkSheet d2p1:Name="Sheet1" xmlns:d2p1="urn:schemas-microsoft-com:office:spreadsheet">
    <Table ExpandedColumnCount="1" ExpandedRowcount="1" TotalColumns="3" TotalRows="1">
      <d2p1:Row>
        <d2p1:Cell><Data ss:Type="String">ID</Data></d2p1:Cell>
        <d2p1:Cell><Data ss:Type="String">Name</Data></d2p1:Cell>
      </d2p1:Row>
      <d2p1:Row>
        <d2p1:Cell><Data ss:Type="Number">1</Data></d2p1:Cell>
        <d2p1:Cell><Data ss:Type="String">Sample</Data></d2p1:Cell>
      </d2p1:Row>
    </Table>
    <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
      <x:Selected />
      <x:Panes>
        <x:Pane>
          <Number>3</Number>
          <ActiveRow>3</ActiveRow>
          <ActiveCol>3</ActiveCol>
        </x:Pane>
      </x:Panes>
      <ProtectObjects>False</ProtectObjects>
      <ProtectScenarios>False</ProtectScenarios>
    </WorksheetOptions>
  </WorkSheet>
</Workbook>

Converting Excel file into XML format

$
0
0

Hi,

My task is to convert the Excel file into XML. I used external Schema file to create XLM mappings in excel andsaved as with XML data format. I was able to save the file without any errors, I am having an issue that when I try to load the same saved XLM file into the network system, its showing the error,"XML file not valid"  and description it says"NO Schema Location found" 

My question are:

1.  If I created the Excel mappings with a XML Schema file, which already had Schema Location in it, shouldn't Schema Location be embedded into generated XML file??

2. If not, then, where should I look for the problem? Is it possible to insert Schema file into the XML? I am using XML Notepad for editing.

I would highly appreciate if anybdy can provide guidance in it.

Thanks,

Yash



XSLT and non-well formed XML file

$
0
0

All,

I am getting some "XML" feeds from some old lab equipment, however the XML isn't well formed.  Really it isn't even XML it is just a formatted text file.  So I will get a feed like the following:

<SampleSet Label="Sample Set"><Name Label="Name" Value="CQS6" /><AnalysisDate Label="Analysis Date" Value="3/13/2015 12:20 PM" /><CarbonAvg Label="Carbon Avg." Value="116 ppm" /></SampleSet><SampleSet Label="Sample Set"><Name Label="Name" Value="2015002301 1" /><AnalysisDate Label="Analysis Date" Value="3/13/2015 11:46 AM" /><CarbonAvg Label="Carbon Avg." Value="43.5 ppm" /></SampleSet><SampleSet Label="Sample Set"><Name Label="Name" Value="2015002302 2" /><AnalysisDate Label="Analysis Date" Value="3/13/2015 11:53 AM" /><CarbonAvg Label="Carbon Avg." Value="44.4 ppm" /></SampleSet><SampleSet Label="Sample Set"><Name Label="Name" Value="2015002303 3" /><AnalysisDate Label="Analysis Date" Value="3/13/2015 12:00 PM" /><CarbonAvg Label="Carbon Avg." Value="42.6 ppm" /></SampleSet><SampleSet Label="Sample Set"><Name Label="Name" Value="2015002322 1" /><AnalysisDate Label="Analysis Date" Value="3/13/2015 12:07 PM" /><CarbonAvg Label="Carbon Avg." Value="32.3 ppm" /></SampleSet><SampleSet Label="Sample Set"><Name Label="Name" Value="2015002323 2" /><AnalysisDate Label="Analysis Date" Value="3/13/2015 12:14 PM" /><CarbonAvg Label="Carbon Avg." Value="35.8 ppm" /></SampleSet><SampleSet Label="Sample Set"><Name Label="Name" Value="2015002324 3" /><AnalysisDate Label="Analysis Date" Value="3/13/2015 12:27 PM" /><CarbonAvg Label="Carbon Avg." Value="32.4 ppm" /></SampleSet><SampleSet Label="Sample Set"><Name Label="Name" Value="CQS6" /><AnalysisDate Label="Analysis Date" Value="3/13/2015 12:33 PM" /><CarbonAvg Label="Carbon Avg." Value="123 ppm" /></SampleSet>

As you can see, this isn't well formed and when I try to process this via XSLT I run into all kinds of problems.  So outside of writting a program to watch for files, picking them up with a c# program, wrapping the XML to make it well formed then pass it to the XSLT file, is there a way that I can wrap the file using XSLT instead of having to create a separate program to make it well formed? Any help is appreciated.

XML Parsing Error: not well-formed (C# Visual Studio 2013)

$
0
0
I am working on a project in visual studio that imports a csv, and exports an xml file. I'd like to be able to get the code to work as xml and html, and view it in a browser. I am getting this error when I load the xml file into a browser:

Firefox
XML Parsing Error: not well-formed Location: file:///C:/Users/fenwky/XmlDoc.xml Line Number 2, Column 6:?> -----^

Chrome
This page contains the following errors: error on line 2 at column 16: colon are forbidden from PI names 'xsl:transform'

This is what my c# code looks like in visual studio 2013:

           // Create a procesing instruction.
            XmlProcessingInstruction newPI;
            // Stylesheet
            String PItext = "<abc:stylesheet xmlns:abc=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">";
            newPI = doc.CreateProcessingInstruction("abc:stylesheet", PItext);
            doc.InsertAfter(newPI, doc.FirstChild);
            // Save document
            doc.Save(xmlfilename);

[UNSOLVED] Event Log Custom XML Query Filtering Help

$
0
0

I've looked at a few different posts but I must be missing something because what I'm constructing isn't working.

Here's the XML code of an example event:

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System><Provider Name="ERAS WCF" /><EventID Qualifiers="0">0</EventID><Level>4</Level><Task>0</Task><Keywords>0x80000000000000</Keywords><TimeCreated SystemTime="2014-07-09T20:32:51.000000000Z" /><EventRecordID>899070</EventRecordID><Channel>Application</Channel><Computer>server.f.q.d.n</Computer><Security /></System>
- <EventData><Data>User username@f.q.d.n has submitted 'Get BIOS Information' operation from servername to computername.f.q.d.n.</Data></EventData></Event>

This is my query:

<QueryList><Query Id="0"><Select Path="Application">*[EventData[Data and (Data='computername' or Data='ip.add.re.ss')]]</Select></Query></QueryList>

I always get 0 results, even if I take stabs in the dark:

  • *[System[(Level=1  or Level=2 or Level=3 or Level=4 or Level=0 or Level=5)]]
  • *[EventData[Data and (Data='*computername*')]]
  • *[EventData[Data and (Data='%computername%')]]

I used this post as my guide for filtering based on contenthttp://blogs.technet.com/b/askds/archive/2011/09/26/advanced-xml-filtering-in-the-windows-event-viewer.aspx

Also:

I hope this is the right place for this question.  This said to post in the server forums, but in the server forums, it said to post here.

I happen to be doing this on a server, but it could just as easily be a desktop.



Convert GMT to EST; HELP!

$
0
0

So, I have an assignment for my coding class and can't seem to figure out why it's outputting the wrong time! I think it has something to do with the time zones...no, i KNOW it has to do with that, but I don't know how to fix it. I've looked online and no one seems to use the code we use. If anybody could help, that'd be awesome. Also, I am trying to figure out how to insert a "0" in front of any single-digit value. For example, if the time is 12:03, I want the minutes place to display "03" and not "3" This is extra credit so I really don't mind if you don't answer that part of the question, but I would appreciate any and all help!

My current code:

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
	int totalSeconds = time(0);
	int currentSecond = totalSeconds % 60;
	int totalMinutes = totalSeconds / 60;
	int currentMinute = totalMinutes % 60;
	int totalHours = totalMinutes / 60;
	int currentHour = totalHours % 12;
	cout << "The current time is: " << currentHour << ":"<< currentMinute << ":" << currentSecond << " GMT" <<
		endl;

system("PAUSE");
}
Thanks, again!

Why I cannot use the following code inside VBA in MS word? What should I do if I want to make that work?

$
0
0
PrivateFunction CreateDOM()Dim domSet dom = New DOMDocument60
    dom.async = False
    dom.validateOnParse = False
    dom.resolveExternals = False
    dom.preserveWhiteSpace = TrueSet CreateDOM = domEndFunctionPrivateSub Form_Load()Dim dom, node, attrOnErrorGoTo ErrorHandlerSet dom = CreateDOM' Create a processing instruction targeted for xml.Set node = dom.createProcessingInstruction("xml", "version='1.0'")
    dom.appendChild nodeSet node = Nothing' Create a processing instruction targeted for xml-stylesheet.Set node = dom.createProcessingInstruction("xml-stylesheet", _"type='text/xml' href='test.xsl'")
    dom.appendChild nodeSet node = Nothing' Create a comment for the document.Set node = dom.createComment("sample xml file created using XML DOM object.")
    dom.appendChild nodeSet node = Nothing' Create the root element.Dim rootSet root = dom.createElement("root")' Create a "created" attribute for the root element and' assign the "using dom" character data as the attribute value.Set attr = dom.createAttribute("created")
    attr.Value = "using dom"
    root.setAttributeNode attrSet attr = Nothing' Add the root element to the DOM instance.
    dom.appendChild root' Insert a newline + tab.
    root.appendChild dom.createTextNode(vbNewLine + vbTab)' Create and add more nodes to the root element just created.' Create a text element.Set node = dom.createElement("node1")
    node.Text = "some character data"' Add text node to the root element.
    root.appendChild nodeSet node = Nothing' Add a newline plus tab.
    root.appendChild dom.createTextNode(vbNewLine + vbTab)' Create an element to hold a CDATA section.Set node = dom.createElement("node2")Set cd = dom.createCDATASection("<some mark-up text>")
    node.appendChild cdSet cd = Nothing
    dom.documentElement.appendChild nodeSet node = Nothing' Add a newline plus tab.
    root.appendChild dom.createTextNode(vbNewLine + vbTab)' Create an element to hold three empty subelements.Set node = dom.createElement("node3")' Create a document fragment to be added to node3.Set frag = dom.createDocumentFragment' Add a newline + tab + tab.
    frag.appendChild dom.createTextNode(vbNewLine + vbTab + vbTab)
    frag.appendChild dom.createElement("subNode1")' Add a newline + tab + tab.
    frag.appendChild dom.createTextNode(vbNewLine + vbTab + vbTab)
    frag.appendChild dom.createElement("subNode2")' Add a newline + tab + tab.
    frag.appendChild dom.createTextNode(vbNewLine + vbTab + vbTab)
    frag.appendChild dom.createElement("subNode3")' Add a newline + tab.
    frag.appendChild dom.createTextNode(vbNewLine + vbTab)
    node.appendChild fragSet frag = Nothing

    root.appendChild node
       ' Add a newline.
    root.appendChild dom.createTextNode(vbNewLine)Set node = Nothing' Save the XML document to a file.
    dom.save App.Path + "\dynamDom.xml"Set root = NothingSet dom = NothingExitSub

ErrorHandler:
    MsgBox Err.Description
EndSub

Access XMLDocument returned from a Web Service

$
0
0

BACKGROUND :
I have xmldocument which has been returned from Land Registry Business Gateway Web Services.
I can successfully access all the returned fields via the Added Service Reference.

QUESTION:
Can I access the XMLDocument directly and if so how?

REASON:
I want to transform it using some XSL, (I know how to do this).
I have searched high and low for this answer but cannot find it anywhere.
Ideally I would like to also write it to a file before transforming it.

I know I could just output the fields in the correct xml format, but I do not think this is necessary as it must already be stored in the returned object in XML format somewhere.

I am sure there is probably a really basic answer to this, help!

XslCompiledTransform.Load takes 15 seconds on first run

$
0
0

Hello,

I'm loading XSL from an XML document using this code (XSL has embedded data):
public void SetHtmlSourceFromXmlDocument(XmlDocument xmlDocument)
{
    var transform = new XslCompiledTransform();
    transform.Load(xmlDocument);

    // ...
}

On customer computers transform.Load(xmlDocument) will take 15 seconds the first time. Subsequent calls will take ~1 ms. Software restart: first call takes again 15 seconds.

This happens only with our server build, a build from my computer (also release) will run just fine (the only thing I know that the server build signs assemblies). This problem also occurs only on non-developer systems (no Visual Studio, no internet access, only intranet). On one of the problematic systems this problem disappeared, but I have no idea why (It seems I did something buy I don't know what, can't reproduce the error on this system anymore).

I also tried transform.Load(xmlDocument, null, null) or supplying my own XmlResolver(GetEntity is never called), because I read that XslCompiledTransform could try to access the xmlns namespace urls to validate the document (maybe I misunderstood that).

I can't install Visual Studio on these machines for debugging. Has someone an idea what could cause this or what I could try to find the issue?

I asked this question a few days ago on stackoverflow (question 29397657) with no luck (can't provide link because I'm not allowed to post links here).

Xml Document:

<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet type="text/xsl" encoding="utf-8" href="#"?><xsl:stylesheet version="1.0" xmlns:data="http://zeiss.com/" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><data:data><calibrationLog><name>DetectorOffsetCalibration</name><entry timestamp="2015-03-25T18:49:24.0313832+01:00" userGroup="Customer" level="Info" indent="0" message="Created at Wednesday, 25 March 2015 18:49:24 (+01 UTC) by Developer on ZEISS-PC." /></calibrationLog></data:data><xsl:template match="xsl:stylesheet"><xsl:apply-templates select="data:data" /></xsl:template><xsl:template match="calibrationLog"><html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><title><xsl:value-of select="name" /></title><style type="text/css"> html, body, p { margin: 0; padding: 0; font-family: Arial; font-size: 12pt; background-color: #FFFFFF;; } p { white-space: pre-wrap; }</style></head><body><h3 style="margin: 0.2em 1em;">Calibration Log "<xsl:value-of select="name" />"</h3><xsl:for-each select="entry"><xsl:variable name="style"><xsl:choose><xsl:when test="@level = 'Debug'">display: none</xsl:when><xsl:when test="@level = 'Info'">color: Black; background-color: White</xsl:when><xsl:when test="@level = 'IntermediateResult'">color: Black; background-color: CornflowerBlue</xsl:when><xsl:when test="@level = 'Result'">color: Black; background-color: YellowGreen</xsl:when><xsl:when test="@level = 'SilentWarning'">color: Black; background-color: Yellow</xsl:when><xsl:when test="@level = 'Warn'">color: Black; background-color: Yellow</xsl:when><xsl:when test="@level = 'Error'">color: White; background-color: OrangeRed</xsl:when><xsl:when test="@level = 'Device'">color: Lightgray; background-color: White</xsl:when><xsl:when test="@level = 'Section'">color: Darkmagenta; background-color: White; font-weight: Bold; border-color: darkmagenta; border-width: 10; border-top-style: Double; border-bottom-style: Double; margin: 0.5em 0; padding-top: 0.3em; padding-bottom: 0.3em</xsl:when><xsl:when test="@level = 'SubSection'">color: Darkmagenta; background-color: White; font-weight: Bold;</xsl:when></xsl:choose></xsl:variable><xsl:variable name="currentIndent" select="1.25 + @indent" /><p style="{$style}; padding-left: {$currentIndent}em; text-indent: -1em;"><xsl:value-of select="@message" /></p></xsl:for-each></body></html></xsl:template></xsl:stylesheet>

Can't Parse in Asp xml file from xmltextwriter.

$
0
0

I don't know a lot about XML, so hang in there please.

Scenario:

A XML file is written in a webservice and returns it to an asp page for parsing.

Returned in the xml.responsetext:

<?xml version="1.0" encoding="utf-8" standalone="no"?> <PartAvailabilityResponse> <OnHand>96</OnHand> <BinLocation>NO BIN</BinLocation> </PartAvailabilityResponse>

Asp Parsing Attempt:

I have tried a number of ways... ways that have been successful before. The only partial success I have had so far is it being seen and read as one element returning   "96 NO BIN"

 Set objLst = CreateObject("MSXML2.DOMDocument")
            objLst.Loadxml (xmlhttp.responseTEXT)
            Set node_list = objLst.documentElement.selectNodes("PartAvailabilityResponse")  Errors:Object required: '[object]'

Tried to see if length will work:

    Set objLst = CreateObject("MSXML2.DOMDocument")
          objLst.Loadxml (xmlhttp.responseTEXT)


response.write "length="&(objLst.length) Errors:Object doesn't support this property or method: 'length'


Tried:  Set objLst =Server.CreateObject("Microsoft.xmlDOM")  same errors

Partial Success:  Returns the result  ..  '96 NO BIN'

 Set objLst = CreateObject("MSXML2.DOMDocument")
            objLst.Loadxml (xmlhttp.responseTEXT)
            set  node_list = objLst.GetElementsByTagName("*")
            ss= node_list.item(0).text
            response.write(ss)    Returns:  96 NO BIN

             response.write "length="&(node_list.length)  Returns: 1

Appreciate any help.



Create XML document nodes

$
0
0

Hi all,

I am trying to create an XML document that looks like this:

<CustomerData><ReferenceInformation><ReturnRef>TESTREF0123</ReturnRef><Action>New</Action></ReferenceInformation><HoldingEntity>TEST12345</HoldingEntity><Profitable>1</Profitable><LocalData><CustomerInfo><CustRef>TEST ACCOUNTReg</CustRef><CustAction>New</CustAction></CustomerInfo><CustomerNumber>99110022</CustomerNumber><OrderData><PurchaseOrder>20</PurchaseOrder><OrderAmount currCode="GBP">1203.00</OrderAmount></OrderData><Contact><FirstName>FirstName</FirstName><LastName>Surname</LastName><Address><StreetName>Street 123</StreetName><City>My City</City><CountryCode>GB</CountryCode></Address></Contact></LocalData></CustomerData>

I need to create multiple items for LocalData. At the moment I am able to do it for one LocalData node using the code below (note I have stripped out a lot in order to send it but I can provide more info.

        private void localData(Customer Info)
        {
            object[] customerItems = new object[] { customerInfo };
            customerItems.Items = accountItems;

            ItemsChoiceType[] accountFieldNames = new ItemsChoiceType[] { correspondingFields };
            customerItems.ItemsElementName = accountFieldNames;
        }

I got a schema done for me and created a class file using xsd.exe which is where I am getting the arrays from.

How best can I achieve what I am looking to do?

Signature namespace prefix

$
0
0

 

Hi,

i am signing XMLs:

....code....

MySignature.ComputeSignature()

MyXmlElement=MySignature.GetXml()

 

and i obtain the famous "<Signature xmlns=http://www.w3.org/2000/09/xmldsig#>"  etc...

 

How can i obtain "<dsTongue Tiedignature xmlnsBig Smiles=http://www.w3.org/2000/09/xmldsig#>" ?

(Note: before ComputeSignature() it is not possible making changes, you know)

I'm very tired surfing for all over the web.

I will pray for a solution (i'm been reading in a lot of forums, etc) haha.

 

 

 

 

 

SignedXml - Signing xml performing custom transform with algorithm "urn://smev-gov-ru/xmldsig/transform"

$
0
0

Hello, fellow colleagues!

I'm trying to sign an XML SOAP request document using SignedXml via detached signature.

In order to pass signature validation I also need to perform two reference transformations. First one is standard XmlDsigExcC14NTransform which I have no problems with. But second one is not provided by Transform class.

This transformation can be performed before passing document to SignedXml but SignedInfo should still contain entry about this transformation in <Transforms> block.

I'm also trying to avoid deriving Transform method.

Is there a way to add a <Transfrom Algorithm="alg"> block with desired transformation algorithm (which by the way is "urn://smev-gov-ru/xmldsig/transform") into SignedInfo without actually performing one and avoid breaking the signature?

So the structure that is to be formed is

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="urn://x-artefacts-smev-gov-ru/services/message-exchange/types/1.1" xmlns:ns1="urn://x-artefacts-smev-gov-ru/services/message-exchange/types/basic/1.1"><soapenv:Header /><soapenv:Body><ns:SendResponseRequest><ns:SenderProvidedResponseData Id="SIGNED_BY_PROVIDER" xmlns:ns="urn://x-artefacts-smev-gov-ru/services/message-exchange/types/1.1" xmlns:ns1="urn://x-artefacts-smev-gov-ru/services/message-exchange/types/basic/1.1"><ns:MessageID>d37b6d00-ed9c-11e4-b80c-0800200c9a66</ns:MessageID><ns:To>3219|x-artefacts-gibdd-gov-ru_breach_root_1.0_BreachRequest|0e8cfc01-5e81-11e4-a9ff-d4c9eff07b77</ns:To><ns1:MessagePrimaryContent><ns2:Response xmlns:ns2="http://ns.rospotrebnadzor.ru/rpnopeka3/1.0.0">1</ns2:Response></ns1:MessagePrimaryContent></ns:SenderProvidedResponseData><ns:CallerInformationSystemSignature><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411" /><Reference URI="#SIGNED_BY_PROVIDER"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />

<!-- this entry is to be added -->

<ds:Transform Algorithm="urn://smev-gov-ru/xmldsig/transform" />

<!-- but the transform is already done outside sthe signing process --></ds:Transforms><DigestMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#gostr3411" /><DigestValue>digest_value</DigestValue></Reference></SignedInfo><SignatureValue>signature_value</SignatureValue><KeyInfo><X509Data><X509Certificate>certificate_info</X509Certificate></X509Data></KeyInfo></Signature></ns:CallerInformationSystemSignature></ns:SendResponseRequest></soapenv:Body></soapenv:Envelope>



XML Reader nullable nodes

$
0
0
You cannot vote on your own post           

Querie for C# forum.   Now posted on XML forum.  Any help welcomed...

I am updating a C# program that uses xmlreader /xmlwrite to serialise the file.

I have a lidtype that is nullable and it works okay  the inlet fails.

   ///<remarks/>

   [System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]

   public System.Nullable<stormwater_pit_lid_type> LidType {

       get {

           returnthis.lidTypeField;

       }

       set {

           this.lidTypeField = value;

       }

   }

publicpartialclass Feature_StormWater_Pit : asset_abstract {

   

   

   private System.Nullable<stormwater_pit_lid_type> lidTypeField;

   privateFeature_StormWater_PitInlet inletField;

   

   privateFeature_StormWater_PitLintel lintelField;

}

Now the lidtype works fine and the null entires seem to be okay.

The inlets are structs in C++ terms…. How can I make them nullable.

publicpartialclass Feature_StormWater_PitInlet {

   

   privatestormwater_pit_inlet_config inletConfigField;

   

   privatestormwater_pit_inlet_type inletTypeField;

   

   ///<remarks/>

   publicstormwater_pit_inlet_config InletConfig {

       get {

           returnthis.inletConfigField;

       }

       set {

           this.inletConfigField = value;

       }

   }

   

   ///<remarks/>

   publicstormwater_pit_inlet_type InletType {

       get {

           returnthis.inletTypeField;

       }

       set {

           this.inletTypeField = value;

       }

   }

}

When the xmlreader serialises this the reader is okay if the fields are all included. However the inlet may not be coded and is code as

<Inletxsi:nil="true"/>

<lintel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">

<Lintelxsi:nil="true"/>

</lintel>

Error no = Cannot add a SimpleContent column to a table containing element

columns or nested relations..

Is there any tricks in getting the structure to be nullable.

With thanks

After C# comments more background from C# post

Thanks for the comments. I am repairing code on a project and this code comes from the xmlreader generated code. The XSD that defines the schema has been defined by the ADAC committee and can't be changed. The data submitted by an external organisation fits the schema but fails in this program. There are close to 1000 fields so it maybe a duplication as you suggest.  I just have to find a solution without changing the xsd and data.

Worse is that there are two xml reader sections in this program to be repaired. One for the first file read and another for subsequent reading of an additional file(merge operation). The second treats the objectid in a different manner. The second reader works and the first fails on the null objects in the inlet node. How do I track down the XMLnode. Seems like he has used XMLDocument. So I am going back to read the initial sample xml reader code today from Microsoft.

The problem defined in the schema: If you have an inlet then you have a inlet type and a linlet material, otherwise you have no inlet (and the field is null). So the inlet can be nullable. The inlet allows water to enter the pit. If the inlet exist it must have an inlet type and property. If it is a closed pit it has no inlet and just a lid on the pit. Thats the definiton in
the schema. The definition looks okay.  So the generated xmlreader seems to set up the classes okay.

So the C# code has been generated and maybe hand massaged. I tried making the inlet nulable but it said it couldn't be nullable. So I pulled out the bit of the code to have as a talking point.

Your answer is similar to the vague answers in the microsoft help. So it is probably right. Maybe there is an inlet for stormwater and an inlet for sewerage that are similar and have been defined either as global or as a child off the tree. The stormater pipe system handles the drainage. The sewerage pipes handle the sewers. We have them as separate systems and separate object types.  The physical world and schema agree.

I have tried for a day to ferret out the changes and can see how part of the xmlreader works.  Global look for inlet and work through the locations.  Do I need to start from scratch with the XMLreader and do a simple case first....

Thanks again for your help


John Keays


John Keays


Create repeating elements in xml document

$
0
0

Good day,

I have a problem with a project I am busy with. I am creating an XML document from a predefined schema. I am able to this with no problem for one level using this method:

{

                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

                XmlSerializer serializer = new XmlSerializer(typeof(UKFATCASubmissionFIReport));
                TextWriter writer = new StreamWriter(destinationPath);
                UKFATCASubmissionFIReport fatcaSub = new UKFATCASubmissionFIReport();
                fatcaSub.SchemaVersion = schemaVersion;

                //Initialize classes and objects
                #region classes and objects

                AccountDataType accountData = new AccountDataType();
                AccountHolderCodeType accountHolderType = new AccountHolderCodeType();
                MessageDataType messageData = new MessageDataType();
                MonetaryType moneyType = new MonetaryType();
                SubmissionType submissionData = new SubmissionType();
                FIReturnActionType fireturnActionData = new FIReturnActionType();
                AccountActionType accountActionData = new AccountActionType();
                TINCodeType tinCode = new TINCodeType();
                HolderTaxInfoType holderInfo = new HolderTaxInfoType();
                //PaymentDataType paymentData = paymentDetails();


                #endregion


                //Monetary type
                moneyType.Value = moneyTypeValue;
                moneyType.currCode = currCode_Type.GBP;

                //Create message data
                messageData.FATCAUserId = FatcaUserID;
                messageData.XMLTimeStamp = timeStamp;
                messageData.MessageCategory = MessageType.NewSubmission;
                fatcaSub.MessageData = messageData;

                //Create submission data object
                submissionData.ReportingPeriod = reportingPeriod;
                submissionData.Item = messageRef;
                fatcaSub.Item = submissionData;

                //FI Return Action

                fireturnActionData.Action = ActionType.New;
                fireturnActionData.FIReturnRef = returnRef;

                //FIReturnActionType[] fireturnItems = new FIReturnActionType[] { fireturnActionData };
                //TIN Code Type
                tinCode.TINCountryCode = countryCode;
                tinCode.Value = tinCodeValue;
                tinCode.TINCountryCodeSpecified = itemSpecified;

                //TIN Information
                holderInfo.ReportableJurisdiction = countryCode;
                holderInfo.TIN = holderTIN;
                holderInfo.TINCode = tinCode;

                //ContactPersonInformation contactInfo = ContactInformation(holderInfo);
                //Contact address
                ContactAddressType contactAddress = new ContactAddressType();
                contactAddress.StreetName = streetName;
                contactAddress.City = contactCity;
                contactAddress.CountryCode = holderInfo.ReportableJurisdiction;

                //Person Details
                ContactPersonInformation contactInfo = new ContactPersonInformation();
                contactInfo.FirstName = firstName;
                contactInfo.LastName = lastName;
                contactInfo.Address = contactAddress;
                contactInfo.HolderTaxInfo = holderInfo;
                contactInfo.BirthDateSpecified = itemSpecified;
                contactInfo.BirthDate = dateOfBirth;

                PaymentMonetaryType paymentMonetary = new PaymentMonetaryType();
                paymentMonetary.currCode = currCode_Type.GBP;
                paymentMonetary.Value = paymentValue;

                //Payment data object
                PaymentDataType paymentData = new PaymentDataType();
                paymentData.PaymentCode = PaymentCodeType.Item20;
                paymentData.PaymentAmount = paymentMonetary;
                //return paymentData;

                //Account action
                accountActionData.AccountRef = accountRef;
                accountActionData.Action = ActionType.New;

                //Account information array
                //AccountData(paymentData, contactInfo, accountActionData, accountData, accountHolderType);

                object[] accountItems = new object[] { accountActionData, accountNumber, paymentData, accountHolderType, contactInfo };
                accountData.Items = accountItems;

                ItemsChoiceType[] accountFieldNames = new ItemsChoiceType[] { ItemsChoiceType.AccountAction, ItemsChoiceType.AccountNumber, ItemsChoiceType.PaymentData, ItemsChoiceType.AccountHolderType, ItemsChoiceType.Person };
                accountData.ItemsElementName = accountFieldNames;

                //Financial Information Return main array
                //FIReturn(submissionData, fireturnActionData, accountData);

                FIReturnType fireturn = new FIReturnType();
                object[] fiItems = new object[] { fireturnActionData, fiRegisterID, dueDilligenceInd, thresholdInd, accountData };
                fireturn.Items = fiItems;

                ItemsChoiceType1[] fiFieldnames = new ItemsChoiceType1[] { ItemsChoiceType1.FIReturnAction, ItemsChoiceType1.FIRegisterId, ItemsChoiceType1.DueDiligenceInd, ItemsChoiceType1.ThresholdInd, ItemsChoiceType1.AccountData };
                fireturn.ItemsElementName = fiFieldnames;

                FIReturnType[] fiData = new FIReturnType[] { fireturn  };
                //Map FI return data to submissionData
                submissionData.FIReturn = fiData;

                //Serialize the submission close the TextWriter

                serializer.Serialize(writer, fatcaSub);

                writer.Close();

                Process.Visible = false;
                MessageBox.Show("Processing Complete!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                Close();

            }

The problem is that I would like fireturn to appear in the document more than once from a dataset. If I changed my code to this:

FIReturnType[] fiData = new FIReturnType[] { fireturn, fireturn, fireturn  };
                //Map FI return data to submissionData
                submissionData.FIReturn = fiData;

I am able to get the three elements as required. How can I change my code to allow for a foreach statement for example?

Support of XML schema 1.1 in .NET

$
0
0

As far as I've seen, .NET does not support XML schema 1.1 (only 1.0), for instance for the validating readers.

There are quite a few nice features in XSD 1.1 and I would like to use them. Are there any plans to include support for XML schema 1.1 anytime soon?

XSD /l:cs /class adac_410.xsd adac_sewer.xsd Multiple files

$
0
0

To XML Forum

This is a new question related to my initial trial to understand how to get a nullable class structure to work in the XMLreader.

I am trying to generate classes from xsd files and in the full ADAC version there are 16 different xsd files.  One for each type of object sewer, storm, water etc and One file for the base generic objects used in most major objects :- a point, a polyline, simple path, complex path for geometry.  Each file name is 30 chars so that is 480 chars for all the names.

I am trying to generate the C# files and it says the line length exceeds 260 chars.  Can I put the file names in a parameter file as one per line.  That is the most common approach to this style of problem.

Is there a simple way to do the XSD so that all the dependencies are obeyed.  The main XSD works on its own.

XSD /l:cs /class adac_v410.xsd adac_sewer.xsd Multiple files

Decided to write a simple reader of the XML file so I can debug the xmlreader and make it verbose as it goes through the file.  I will just write out a simple text file of the values to test the file structure.

With thanks...

John Keays


John Keays

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.


DataContractSerializer and xsd classes

$
0
0

Hello everyone,

I have this very devious class hierarchy that is supposed to be saved as an XML file. I found that the DataContractSerializer is quite suitable for this objects (or at least as suitable as the XAML servcies), so I went ahead and added the DataContract and DataMember attributes to all the items in the class hierarchy.

Now, the problem is, one of the classes in this hierarcy references another class (which is outside), defined in an xsd file (created with visual studio editor). The class is a nested class (yup). The topmost class inherits from DataSet, the nested class inherits from DataRow. I couldn't find any way of adding the required attributes for the DataContractSerializer, as the designer will undo all my changes upon build (since the file is automatically generated).

How can I serialize this class along with my other classes? Apparently, DataSet has a method that write XML directly, but i can't find a way to make it work with DataContractSerializer :(

The application makes heavy use of datagridview and all teh related data controls. This is probably the reason why it uses a database and xsd in the first place (i am not the one who designed it btw). 


Viewing all 935 articles
Browse latest View live


Latest Images

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