473,398 Members | 2,165 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Creating XML Element

I'm trying to create Element as following name

MyElement:InitialName

XmlElement elem = doc.CreateElement("MyElement:InitialName");

when generate the XML the tag is truncated as ONLY "MyElement",why?

Any Suggestions

Nov 12 '05 #1
4 2102


Raed Sawalha wrote:
I'm trying to create Element as following name

MyElement:InitialName

XmlElement elem = doc.CreateElement("MyElement:InitialName");

when generate the XML the tag is truncated as ONLY "MyElement",why?


A name with a colon is a qualified name where the part before the colon
is a prefix that needs to be bound to a namespace URI so you need to
decide which namespace you want that element to be in and then use a
second parameter to CreateElement to pass in the namespace URI
XmlElement elem = doc.CreateElement("MyElement:InitialName",
"namespace URI goes here")

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Nov 12 '05 #2
the real problem i have that when created the element as following:

XmlElement elem = doc.CreateElement("imsmd:lom","x");

it is generated as
<imsmd:lom xmlns:imsmd="x">info</imsmd:lom>

but what i need is

<imsmd:lom>info</imsmd:lom>

how can I achieve this?>

"Martin Honnen" wrote:


Raed Sawalha wrote:
I'm trying to create Element as following name

MyElement:InitialName

XmlElement elem = doc.CreateElement("MyElement:InitialName");

when generate the XML the tag is truncated as ONLY "MyElement",why?


A name with a colon is a qualified name where the part before the colon
is a prefix that needs to be bound to a namespace URI so you need to
decide which namespace you want that element to be in and then use a
second parameter to CreateElement to pass in the namespace URI
XmlElement elem = doc.CreateElement("MyElement:InitialName",
"namespace URI goes here")

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/

Nov 12 '05 #3


Raed Sawalha wrote:
the real problem i have that when created the element as following:

XmlElement elem = doc.CreateElement("imsmd:lom","x");

it is generated as
<imsmd:lom xmlns:imsmd="x">info</imsmd:lom>

but what i need is

<imsmd:lom>info</imsmd:lom>
But that is not well-formed XML with namespaces, if you have a prefix
(e.g. imsmd) then you need to bind it to a namespace URI.
how can I achieve this?>


As said you need to have
<imsmd:lom xmlns:imsmd="x">info</imsmd:lom>
to comply with XML with namespaces rules.

Why do you want the name
imsmd:lom
? In theory if you use XML without namespaces then such element names
are allowed but nowadays most implementations for DOM implement the
rules of XML with namespaces and there if you have a colon the first
part is a prefix and you need to bind it to a URL.
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Nov 12 '05 #4
"Raed Sawalha" <Ra*********@discussions.microsoft.com> wrote in message news:1E**********************************@microsof t.com...
the real problem i have that when created the element as following:

XmlElement elem = doc.CreateElement("imsmd:lom","x");

it is generated as
<imsmd:lom xmlns:imsmd="x">info</imsmd:lom>

but what i need is

<imsmd:lom>info</imsmd:lom>

how can I achieve this?


Martin's response is correct: the xmlns belongs there in XML with namespaces.

I have observed only a handful of application development areas (such as XML
editors and text processors), in which developers sometimes have an interest in
stripping out the extra xmlns declarations. For instance, they might be copying
the 'piece of text' they've gotten from OuterXml to somewhere else within the
same text stream, and they know the destination is already going to have the
necessary xmlns decls in-scope. Another example is maybe the application
is mapping an underlying XmlDocument node tree to the text representation
in an edit window, and they must pass a portion of text corresponding the
selected nodes to the DrawString( ) method in GDI+ to re-paint the invali-
dated part of the display.

One way to get around these xmlns declarations is just to strip out any xmlns,
like the following filtering StreamWriter subclass does,

- - - XmlNsFilterWriter.cs
using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace Derek
{
/// <remarks>
/// XmlNsFilterWriter strips out all xmlns declarations present
/// in XML fragment string representations.
/// </remarks>
public class XmlNsFilterWriter : StreamWriter
{
protected Stream outs;

/// <summary>
/// Creates a filter to strip xmlns attributes around a stream that is an XML fragment.
/// </summary>
/// <param name='s'>
/// a sink to filter writes into.
/// </param>
public XmlNsFilterWriter( Stream s) : base( s)
{
outs = s;
}

/// <summary>
/// Eliminates occurrences of the substring " xmlns[:prefix]=/nsuri/" in the string
/// by advancing the cursor, p, past them.
/// </summary>
/// <param name='s'>
/// a well-formed XML string to filter.
/// </param>
/// <param name='p'>
/// a position index that is modified.
/// </param>
/// <throws cref='System.FormatException'>
/// an xmlns declaration was found but it was missing an expected quote delimiter.
/// </throws>
protected void filterXmlNs( string s, ref int p)
{
char quoteMark; // could be dbl or single.
p += 7; // strlen( " xmlns(:|=)") == 7.

try
{
while ( s[p] != '"' && s[p] != '\'' )
{
++p;
}
quoteMark = s[p];
while ( s[++p] != quoteMark )
{
;
}
++p;
}
catch ( IndexOutOfRangeException ioore)
{
Debug.Assert( false, "Closing xmlns quotation mark expected but" +
"not found in XmlNsFilterWriter.filterXmlNs( )");
throw new FormatException( "Bad xmlns syntax in output stream.", ioore);
}
}

public override void Write( string s)
{
StringBuilder sb = new StringBuilder( );
int pos = 0;
int len = s.Length;
int endOfSearchIdx = len - 7;

// Within 7 characters of end-of-string, finding
// an xmlns declaration is impossible.
//
while ( pos < endOfSearchIdx )
{
bool inTextContent = true;

// Don't look for " xmlns" between > and <, since
// it would be text content not an attribute value.
//
if ( !inTextContent && s[ pos] == '>' )
{
inTextContent = true;
}
else
{
// This would be &lt; if it were intended
// to be in the text content.
//
if ( inTextContent && s[ pos] == '<' )
{
inTextContent = false;
}
}

// Check to see if this is the start of an xmlns
// attribute.
//
if ( !inTextContent && ( s.Substring( pos, 6).CompareTo( " xmlns") == 0 ) )
{
// Set pos 1 past closing quote.
//
filterXmlNs( s, ref pos);
}
sb.Append( s[ pos]);
++pos;
}
// Copy last zero to six chars.
sb.Append( s, pos, ( len - pos));

byte[] buf = new UTF8Encoding( ).GetBytes( sb.ToString( ));
outs.Write( buf, 0, buf.Length);
}
}
- - -

Now to print your XmlElement, elem, to the console without the xmlns but with any
prefix, you could write something like this,

XmlNsFilterWriter filter = new XmlNsFilterWriter( Console.OpenStandardOutput( ));
Console.SetOut( filter);
Console.Write( elem.OuterXml);

What this does is wrap the afforementioned StreamWriter around stdout (so every
output call going to stdout, or any other Stream you wrap XmlNsFilterWriter
around, passes through XmlNsFilterWriter). The overrides on certain methods
of StreamWriter in XmlNsFilterWriter keep track of state and pinpoint times when
the text "xmlns..." is being written out. All XmlNsFilterWriter does is eat those
chars, and pass the rest of the Stream through to your console undisturbed.

Note that this XmlNsFilterWriter is a little "strip-happy," in that it will strip all the
xmlns declarations. Occassionally, there may be some xmlns declarations you
want to keep. For instance, if the node is the top-level node in which that xmlns
first comes into scope, you may need its declaration. Handle this by checking
it's parent node to see if a namespace URI being removed is also in-scope on
the parent. If it is then it may be safe to take it from the child. If it's not then
the child is probably responsible for having the xmlns declaration.

Again, the actual number of real XML applications where something like this
applies are few and far between. Normally, you should want to keep the xmlns.

I'd be interested in hearing just what the application area is where you need the
xmlns taken out (as you can tell, I keep a list on this particular problem, and to
date it's a very short list).
Derek Harmon
Nov 12 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: gonzalo briceno | last post by:
I have been using phplib for a while and I really like the framework except for form creation. Maybe it is me but I in my opinion there isn't a good way to create forms or should I say, everything...
0
by: Brett Selleck | last post by:
We have an issue where the JAXB generated classes are creating an interface which references itself. The Schema is valid, and I have not seen this ran into before. The code is below. What is...
0
by: Fendi Baba | last post by:
Hi everyone I am new in this so please bear with me. I am trying to create a schema for a Quotation document. I created the creating the forms using Microsoft Infopath. I am creating my own...
1
by: Chris Kennedy | last post by:
How do create a dataset from scratch based on an XML schema. This will not be filled by a dataadapter. It will be a dataset which I add rows to and then save as an XML file. All the example depend...
0
by: Mark Broadbent | last post by:
can someone help me? After creating an xml schema file in VS 2003, I drag and drop a table onto it to create its schema. However what I am getting is a document element encapsulating the actual...
0
by: Mark Broadbent | last post by:
(firstly sorry Ive cross posted this in C# forum also -I forgot to include this ng) can someone help me? After creating an xml schema file in VS 2003, I drag and drop a table onto it to create...
2
by: pshvarts | last post by:
(I'm new in SOAP) I get some wsdl file (from apache service ). I tried creating SOAP client with .NET - trying to add Web Reference and get error like: "Custom tool error: Unable to import...
7
by: Michael Williams | last post by:
Hi All, I'm looking for a quality Python XML implementation. All of the DOM and SAX implementations I've come across so far are rather convoluted. Are there any quality implementations that...
4
by: Michel Verhagen | last post by:
Hi, I want to create a DTD in an XML file in memory. The XML file is created using the DOM in C#. I am new to all this, but couldn't find anything about creating DTD's using the DOM (well, I...
2
by: Moses | last post by:
Hi All, Is is possible to catch the error of an undefined element while creating an object for it. Consider we are not having an element with id indicator but we are trying to make the object...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.