CDATA and XmlNode

Hello,

I have the following code:

       // Read the XML document from the hard-drive.
        XmlDocument doc = new XmlDocument();
        doc.Load("doc.xml");

        // Create the document's root.
        XmlElement root = doc.DocumentElement;

        // Filter the node we want.
        XmlNodeList nodes;
        nodes = root.SelectNodes("/Pages/Page[@Filename='" + id + "']");
        XmlNode node = nodes[0];

        // Retrieve data from the node
        m_Filename = id;
        m_Caption = node["Caption"].InnerText;
        m_Content = node["CDATA"].InnerText;  // ??????????????

The problem is that m_Content needs to be populated from CDATA section of
the selected node. There is no <CDATA></CDATA> element so this code fails.

How to do this?

Thanks,
Leszek Taratuta




0
Leszek
1/22/2004 3:00:42 PM
dotnet.xml 7266 articles. 0 followers. Follow

2 Replies
724 Views

Similar Articles

[PageSpeed] 13

Hi Lesek,

Below is some sample code to acess a CDATA section:

string fileName = "test.xml";
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlElement root = doc.DocumentElement;
XmlNode node = doc.DocumentElement.SelectSingleNode(
    @"/Computers/Computer[@Manufacturer='Gateway']/CPU");
XmlNode childNode = node.ChildNodes[0];
if (childNode is XmlCDataSection)
{
    XmlCDataSection cdataSection = childNode as XmlCDataSection;
    Console.WriteLine(cdataSection.Value);
}

The XML File is shown below:
<Computers>
    <Computer Manufacturer="Dell">
    <CPU>
    Intel Pentium 4
    </CPU>
    </Computer>
    <Computer Manufacturer="Gateway">
        <CPU>
            <![CDATA[
                    this is the <CData Text>
            ]]>
        </CPU>
    </Computer>
</Computers>

I hope this helps,

Bennie Haelen

"Leszek" <taratuta@5thbusiness.com> wrote in message
news:OKa64dP4DHA.2480@TK2MSFTNGP09.phx.gbl...
> Hello,
>
> I have the following code:
>
>        // Read the XML document from the hard-drive.
>         XmlDocument doc = new XmlDocument();
>         doc.Load("doc.xml");
>
>         // Create the document's root.
>         XmlElement root = doc.DocumentElement;
>
>         // Filter the node we want.
>         XmlNodeList nodes;
>         nodes = root.SelectNodes("/Pages/Page[@Filename='" + id + "']");
>         XmlNode node = nodes[0];
>
>         // Retrieve data from the node
>         m_Filename = id;
>         m_Caption = node["Caption"].InnerText;
>         m_Content = node["CDATA"].InnerText;  // ??????????????
>
> The problem is that m_Content needs to be populated from CDATA section of
> the selected node. There is no <CDATA></CDATA> element so this code fails.
>
> How to do this?
>
> Thanks,
> Leszek Taratuta
>
>
>
>


0
haelenb (3)
1/23/2004 2:10:40 AM
Thanks.
Your code works great.

Leszek

<haelenb@bellsouth.net> wrote in message
news:eMLnbYV4DHA.2384@TK2MSFTNGP10.phx.gbl...
> Hi Lesek,
>
> Below is some sample code to acess a CDATA section:
>
> string fileName = "test.xml";
> XmlDocument doc = new XmlDocument();
> doc.Load(fileName);
> XmlElement root = doc.DocumentElement;
> XmlNode node = doc.DocumentElement.SelectSingleNode(
>     @"/Computers/Computer[@Manufacturer='Gateway']/CPU");
> XmlNode childNode = node.ChildNodes[0];
> if (childNode is XmlCDataSection)
> {
>     XmlCDataSection cdataSection = childNode as XmlCDataSection;
>     Console.WriteLine(cdataSection.Value);
> }
>
> The XML File is shown below:
> <Computers>
>     <Computer Manufacturer="Dell">
>     <CPU>
>     Intel Pentium 4
>     </CPU>
>     </Computer>
>     <Computer Manufacturer="Gateway">
>         <CPU>
>             <![CDATA[
>                     this is the <CData Text>
>             ]]>
>         </CPU>
>     </Computer>
> </Computers>
>
> I hope this helps,
>
> Bennie Haelen
>
> "Leszek" <taratuta@5thbusiness.com> wrote in message
> news:OKa64dP4DHA.2480@TK2MSFTNGP09.phx.gbl...
> > Hello,
> >
> > I have the following code:
> >
> >        // Read the XML document from the hard-drive.
> >         XmlDocument doc = new XmlDocument();
> >         doc.Load("doc.xml");
> >
> >         // Create the document's root.
> >         XmlElement root = doc.DocumentElement;
> >
> >         // Filter the node we want.
> >         XmlNodeList nodes;
> >         nodes = root.SelectNodes("/Pages/Page[@Filename='" + id + "']");
> >         XmlNode node = nodes[0];
> >
> >         // Retrieve data from the node
> >         m_Filename = id;
> >         m_Caption = node["Caption"].InnerText;
> >         m_Content = node["CDATA"].InnerText;  // ??????????????
> >
> > The problem is that m_Content needs to be populated from CDATA section
of
> > the selected node. There is no <CDATA></CDATA> element so this code
fails.
> >
> > How to do this?
> >
> > Thanks,
> > Leszek Taratuta
> >
> >
> >
> >
>
>


0
Leszek
1/23/2004 3:17:02 PM
Reply:

Similar Artilces:

How to serialize a string as a CDATA attribute ?
Hi, the below string will have often char like < & etc. so I need to serialize it as CDATA. Unfortuntalety there is no CDATA type for the XmlAttribute(Type=... How can I get this serialized to a CDATA string ? /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string HotelName { get { return _HotelName; } set { _HotelName = value; } } private string _HotelName; > Hi, > > the below string will have often char like < & etc. so I need to > serialize it as CDATA. Unfortuntalety there is no CDATA type for the >...

SetAttribute method does not exist for my XmlNode object
I am having trouble creating an Attribute on a new node. The NodeObject.SetAttribute(x,y) method does not exist for the "RecordElement" node. What am I missing??? Earl XmlDocument d = new XmlDocument(); d.Load(savepath); XmlNode RootNode = d.DocumentElement; //CREATE THE RECORD NODE XmlNode RecordElement = d.CreateElement("RECORD"); //RecordElement.SetAttribute(name, value) does not exist here Earl Teigrob wrote: > I am having trouble creating an Attribute on a new node. The > NodeObject.SetAttribute(x,y) method does not exist for the "RecordElement...

Error:An unexpected end of file parsing CDATA has occurred.
I am creating a XML document which opens fine in IE. Implies MSXML thinks it is a well formed document. But when I try to load this document in VB.net using the following code Dim doc As New XmlDocument doc.Load("C:\Projects\SQLXML\corc.xml") I get the following error: "System.Xml.XmlException: An unexpected end of file parsing CDATA has occurred. Line 6, position 1. at System.Xml.XmlScanner.ScanCData() at System.Xml.XmlScanner.ScanMarkup() at System.Xml.XmlTextReader.ParseTag() at System.Xml.XmlTextReader.ParseBeginTagExpandCharEntities() at System.Xml.XmlTextR...

Effectient way to encode CDATA elements
Ok, I'm reading data from a stream using a StreamReader. The data inside the stream is not xml, it could be anything. Based on the input StreamReader I'm writing to an output stream using an XmlTextWriter. Basically, when all is said and done, the output stream contains data from the input stream wrapped in a element contained in a parent element. My problem is twofold. Data gets read from the input stream in chunks, and the StreamReader class returns char[]. If data in the input stream contains a "]]>" it needs to be split across two CDATA elements. First, how do ...

XML CDATA etc
Hello NG, I am getting some information from DB, and that data has mix html and XML tags in the content (e.g. detail on country). Basically CDATA types are mixed with regular string. Also, html tags are in escape form (e.g. > is &gt;). When I display that string I see those tags. Basically I am getting all this data as xml form and I want to find out how can I change those html tags into regular tags, and also how to remove CDATA or any instructions in the string. Is there a quick way to do that? My problem is increased as I don't know XML. Thank you, Po JohnAD wrote: &g...

CDATA and XmlNode
Hello, I have the following code: // Read the XML document from the hard-drive. XmlDocument doc = new XmlDocument(); doc.Load("doc.xml"); // Create the document's root. XmlElement root = doc.DocumentElement; // Filter the node we want. XmlNodeList nodes; nodes = root.SelectNodes("/Pages/Page[@Filename='" + id + "']"); XmlNode node = nodes[0]; // Retrieve data from the node m_Filename = id; m_Caption = node["Caption"].InnerText; m_Conten...

CDATA
I have the XML file content as <resources> <html><![CDATA[<B>Hello World</B>]]></html> </resources> and my html file content is <html><![CDATA[<B>Hello World</B>]]></html> the XML file when viewed doesnt give me any problem, but when it comes to HTML the output that i recieve is Hello World]]> In order to remove the square bracket and the angle bracket in the HTML I make the following correction: HTML: <html><![CDATA[<B>Hello World</B></html> XML: <resources> <html>...

CDATA delimiter within CDATA Section
How can the CDATA ending delimiter "]]>" be represented within a CDATA section itself? Consider an XML document that is intended to contain an embedded, uninterpreted XML example. Generally, the easiest way to represent it would be to put the embedded XML example inside a CDATA section. But if the example has a CDATA section itself, then the ending delimiter will be interpreted as the end of the "real" CDATA section. Here's even a simpler example with a script's conditional statement: <test> <!CDATA[ ... if g[a[i]]>f ... ... ]]>...

Finding & Updating nodes within a CDATA section
This is a multi-part message in MIME format. ------=_NextPart_000_0011_01C59103.2AA08720 Content-Type: multipart/related; type="multipart/alternative"; boundary="----=_NextPart_001_0012_01C59103.2AA08720" ------=_NextPart_001_0012_01C59103.2AA08720 Content-Type: multipart/alternative; boundary="----=_NextPart_002_0013_01C59103.2AA08720" ------=_NextPart_002_0013_01C59103.2AA08720 Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable BlankI seem to be able to find and update nodes and attributes fairly = we...

CDATA string?
I have a string that is returned from a web service that is XML so the string is enclosed in CDATA[![ . . . ]]. The string/data enclosed in the CDATA section is real XML. If I try to LoadXml into an XmlDocument I get an exception. Does anyone have suggestions on how I can strip the CDATA off of the string so I can load the real XML into an XmlDocument? Thank you. Kevin Hello! > I have a string that is returned from a web service that is XML so the string > is enclosed in CDATA[![ . . . ]]. The string/data enclosed in the CDATA > section is real XML. If I try to LoadXml in...

CDATA Headache
This is a multi-part message in MIME format. ------=_NextPart_000_009B_01C39E14.2CF823E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi: Do you know how to add a CDATA node to XmlElement and retrieve it from = XmlElement? Thanks, Dennis ------=_NextPart_000_009B_01C39E14.2CF823E0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META http-equiv=3DContent-Type content=3D&quo...

Using CDATA section in an Import file.
I have an opportunity import file that contains data (such as, "{") that needs to be wrapped with a CDATA section. Can I wrap the entire file <ImportExportXml version="3.0.5300.0"> <![CDATA[ <Entities> <Entity> <Name LocalizedName="Project" OriginalName="Opportunity">Opportunity</Name> <ObjectTypeCode>3</ObjectTypeCode> .. .. .. and so on ... .. ]]> </ImportExportXml> Thanks. ...

CDATA for XmlTextAttribute
After serialzing I want, <MyRequest> <Content SigningScheme="pkcs7"><![CDATA[JFHSKDKFJ869KJ7hk96HKKghgfk46294857J]]></Content> </MyRequest> _________________________________________________________________________________________ My class looks like, public class Content { private string _signingScheme; private string _payLoad; [XmlAttribute("SigningScheme")] public string SigningScheme { get { return _signingScheme; } set { _signingScheme = value; } } [XmlText] public string PayLoad // stuff that need...

XmlNode.SelectNodes, order of nodes
If I execute XmlNode.SelectNodes("some xpath query") and then use foreach to iterate over it. Will it guaratee that the order of nodes I get will be same as the order of nodes in the original xml document? Can someone point me to a document which states that the order is (or is not) guarateened (I could not find any when i did my search on msdn). This is very crucial to our design, otherwise I will have to add a "sequence" attribute and then order by the sequence. Thanks in advance. -- Vikram Vamshi Database Engineer Eclipsys Corporation Vikram Vamshi wrote: &...

XmlSerializer, XmlAnyElement and CDATA
(VS.NET 2K3, C#) Hi, I need to serialize/deserialize an element using XmlSerializer that can contain any valid XML including a CDATA section. [XmlRootAttribute] public class Test { [XmlAnyElement] public XmlElement Anything; } This doesn't work with an XML like the following: <Test><![CDATA[ msgbox "Hi222"]]></Test> However this works fine: <Test><Wrap><![CDATA[ msgbox "Hi222"]]></Wrap></Test> Unfortunately in my case the XML between <Test> comes from outside of my application and can contain virtually anything...

CDATA in RSS title and description?
Does it seem to be a general consensus that CDATA within the title and the description is widely supported at this point in time is a means to allow users to submit data such as the word AT&T in an RSS title or description? What are the known generally accepted pitfalls of using CDATA? -- <%= Clinton Gallagher NET csgallagher AT metromilwaukee.com URL http://clintongallagher.metromilwaukee.com/ clintonG wrote: > Does it seem to be a general consensus that CDATA within the title > and the description is widely supported at this point in time is a > me...

XML Serialization and CDATA
Hi... I am trying to Serialize a class using XmlSerializer. The problem is, I have a property in which I store HTML data, and I want to include id in the XML as a CDATA node. Any suggestions? Thanx in advance John Pouliezos wrote: > I am trying to Serialize a class using XmlSerializer. The problem is, I > have a property in which I store HTML data, and I want to include id in > the XML as a CDATA node. Any suggestions? The easiest way is to pass resulting XML via the following XSLT: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="...

Writing CDATA data to XML
Hi folks! I have a DataSet, which I'm writing into XML using the DataSet.WriteXML() method. Now, I want to write the cell's data/text as CDATA, when it is written into an XML. For example, I want the XML output as follows: <root> <myElement><![CDATA[abc]]></myElement> </root> but not... <root> <myElement>&lt;![CDATA[abc]]&gt;</myElement> </root> Is this possible? thanks! -Yasutaka That is what native "DataSet.WriteXML()" got you ? The MS coders must have had a day off. "Yasutaka Ito" <...

Struggling with XML CDATA
I have looked at several articles and help on reading CDATA from an XML node but cant say I understand it. I dont want to itereate through all subnodes to find the CDATA. Is there a way in VB.NET to just query that section directly and read it for each MSG node? My XML looks something like this: <MSG ID="8W"> <ROAD SEGLEN="2"/> <ROAD SEGLEN="5"/> <ROAD SEGLEN="2"/> <![CDATA[ READING TAKEN BY NSH. TRUCK ]]> </MSG> <MSG ID="9W"> <ROAD SEGLEN="3.5"/> <ROAD SEGLEN="1"/> &l...

Converting an object into an XmlNode
Hi, Is there a clean way to build up an XML Node from an object? What I am presently doing to create the node is: 1. Create a StringWriter and then use XmlSerializer to serialize the object into that StringWriter. 2. Create a new XmlDocument called tempDoc and call tempDoc.LoadXml(stringWriter.ToString()) 3. Create an XmlNode by calling myDoc.ImportNode (tempDoc.LastChild, true) Then I call AppendChild() to add this new node into the correct position in myDoc. Is there a cleaner way to do this? For example, is there an XmlNodeWriter or equivalent? Thanks Hari Hari Menon wrote: >...

Parse CDATA in XML Document
Hi, I have an XML doc as below <WebSRFTemplate Version="1" Type="SERVICE"> <Data> <Field Name="SERVICEStaticRoute2IPnetwork1"><![CDATA[Test]]></Field> </Data> </WebSRFTemplate> I load this into an XmlDocument using C# I then create an XPathNavigator using my XmlDocument. How do I get the CDATA using my XPathNavigator? C wrote: > <WebSRFTemplate Version="1" Type="SERVICE"> > <Data> > <Field Name="SERVICEStaticRoute2IPnetwork1"><![CDATA[Test]]></...

XmlNode.ChildNodes Bug????
Hi, I just tried to replace a single XmlNode with several ChildNodes. When doing this with the following code i found out that if you get the ChildNodes with 'ChildNodes' - property the nodes get removed. Is this possibly a Framework Bug?? foreach( XmlNode node in oldNode.ChildNodes ) { newNode.AppendChild( node ); } parent.ReplaceChild( newNode, oldNode ); After doing several Tests is tried it the following way and it worked fine. [code:1:f2d0f1e03d] for( int i = 0; i < oldNode.ChildNodes.Count; i++ ) { XmlNode node = oldNode.ChildNodes[ i ]; newNode.AppendC...

How to insert a CDATA section using XPathNavigator ?
Can anybody show me how to insert a CDATA section using XPathNavigator ? I have tried the follwing with no luck: XmlDocument docNav = new XmlDocument(); docNav.LoadXml(xmlString); XPathNavigator nav = docNav.CreateNavigator(); XmlDocument doc = new XmlDocument(); doc.LoadXml("<DocumentData></DocumentData>"); XmlElement elem = doc.CreateElement(currentNodeName); elem.AppendChild(doc.CreateCDataSection(dataString)); doc.DocumentElement.AppendChild(elem); XPathNavigator newNav = doc.CreateNavigator(); nav.InsertAfter(newNav); Regard...

Serialize XmlNode in an ArrayList
Hi all, When I try to use XmlSerializer to serialize an ArrayList object which contains XmlNode objects, I got the "InvalidOperationException: The type System.Xml.XmlElement may not be used in this context." I can serialize an ArrayList object with string value and also an XmlNode object individually without problem. I have no idea why these two together can't work. Any advice will be appreciated. Thanks. Here is the sample code I am testing on: ------------------------------------------------ ArrayList oArr = new ArrayList(); XmlDocument oXML = new XmlDocument(); ...

Cannot implicitly convert type 'object' to 'System.Xml.XmlNode'
Hi, I have a problem with XmlNodes and my stack. It looks something like this: //declarations XmlNode node, new_node; Stack MyStack = new Stack(); //code MyStack.Push(node); new_node=MyStack.Pop(); The last line delivered an error like this: Cannot implicitly convert type 'object' to 'System.Xml.XmlNode' Could somebody please tell me what I'm doing wrong? Thank you. Svyatoslav wrote: > I have a problem with XmlNodes and my stack. > It looks something like this: > > //declarations > XmlNode node, new_node; > Stack MyStack = new Stack(); > >...