serialize attribute without value in C# [duplicate] - c#

I want to have an XML attribute without any value, which simply has one meaning when it exists or does not exist.
Is that valid?

An attribute must be specified with the following syntax:
Name Eq AttValue
where Name is a legal XML name, Eq is = optionally preceded or followed by whitespace, and AttValue is a legal attribute value.
This definition is true for both XML 1.0 and XML 1.1.
If you are trying to specify an attribute as below:
<car owned/>
then no, that is not valid. If you are trying to specify it this way:
<car owned=""/>
then yes, that is valid.

No.
Boolean attributes in XML are of the form foo="foo".
Even in SGML, you must provide the value, (it is the name, = and quotes that you can omit, which is why you have things like <select multiple> in HTML).

You can have an attribute whose only permitted value is the empty string, "". I'm not sure it's good design, though; I would normally suggest a boolean attribute with values true/false, and a default value of false.

Related

Can I use quote marks in an XML documentation comment?

When writing an XML documentation comment in a C# source file, do I need to replace " with "? This question discusses how to replace characters, but does not establish which characters need replacing, aside from establishing that angle brackets do need replacing.
No, just like normal XML, you only need to escape the quotes when they would otherwise have a special meaning. So if your XML documentation contains an attribute and you want a double quote in the attribute value, then you'd either use an attribute or use a single quote for the value start/end:
/// Foo <element attr="Bar"Baz" />
/// Foo <element attr='Bar"Baz' />
But it's very rare to need attribute values with quotes in within XML documentation, in my experience. They're almost always references to parameters, members, or list types.

Do not serialize empty strings to XML

I've got a library project where object are serialized to XML format for further download by users in ASP.NET application. Additionaly i've used XSD to generate types for serialization. The number of types for serialization is very big. Each type is serialized to its own XML. Some types have string properties, sometimes those properties contains empty strings. During serializations those properties are been serialized to some like this
<propertyName />
So this properties become invalid by XSD (they are not required but have some restrictions like string minimal string length etc.
Is there any way to configure XMLSerializer not no serialize empty strings to empty xml elements for all types that are been serialized.
For serializing I use System.Xml.XmlSerializer.
You'd need to implement xml writer/reader for the serializations to work;
You would also need to edit the writer and reader to work on conditionals, first check if a param is an empty string before writing a new xml element and placing its value.
if(string.isNullOrEmpty(this.testString)){
break; // if in a loop of params, just giving an example, rest of the
// xmlwriter implementation would be normal
// note you might need to also implement the reader a bit different - unsure of that.
}
Reference material:
http://forum.codecall.net/topic/58239-c-tutorial-reading-and-writing-xml-files/
http://www.dotnetperls.com/xmlwriter
I would advise you to go back and read the XML specification carefully. See http://www.w3.org/TR/REC-xml/#sec-starttags
where it says:
[Definition: An element with no content is said to be empty.] The representation >of an empty element is either a start-tag immediately followed by an end-tag, or
an empty-element tag. [Definition: An empty-element tag takes a special form:]
So this:
<propertyName />
is exactly equivalent to this:
<propertyName></propertyName>
...and any XML processor that treats them differently is not conforming to the specification.
I find that people often confuse the following concepts when dealing with XML and XML schema:
tag with empty content.
Either form is acceptable. Empty is not the same as 'null' or 'nil'.
An element is allowed to be empty or nil even if minOccurs=1 in the schema.
null value / nil value.
Not the same as empty content. XML has a specific attribute to indicate that the value is 'nil'.
missing tag.
The tag is entirely omitted from the XML document. Not the same as empty or nil.
This will trigger a validation error if minOccurs=1
If you are fetching data from database then you can apply if condition like :-
if (Dbobject.propertyName == ""){
XMLObject.propertyName = null;
} else {
XMLObject.propertyName = Dbobject.propertyName;
}
The null values will not be serialized and the property name will be skipped during XML Serialization.

Avoid escaping illegal charactes when set an XmlAttribute value

The problem is when a try to set an XmlAttribute value with the '>' char. It escape with the value '>', but '>' es valid because it is into an attribute value. Example:
var element = xmlDoc.CreateElement("Studient");
element.SetAttribute("Year", ">3");
xmlDoc.DocumentElement.AppendChild(element);
xmlDoc.Save(csprojPath);
In this case it produce <Studient Year=">3" xmlns="" />. How can i get <Studient Year=">3" xmlns="" /> ?
As far as I know, There is no way to create the data like ">3" in attribute value. If you open created XML in reader it will display as ">3" only. If you are parsing XML in code , you can easily convert to intended meaning.
If you can use Section value instead of Attribute Value for Student Year, you can use XmlCDataSection by CreateCDataSection (for example: https://msdn.microsoft.com/en-us/library/vstudio/system.xml.xmldocument.createcdatasection(v=vs.100).aspx)

How to force XmlSerializer to generate an empty tag when a condition is met?

I have an XSD from another company which forces me to generate empty tags in the Xml. I've created a class based on this XSD with XSD.exe. One of the properties is a DateTime property. In my case I don't need this property, so I set it's value to DateTime.MinValue. This, offcourse, generates a tag with the min value as a value.
What I want is that while serializing a check takes place: if the value equals the min value, then generate an emptye tag, otherwise create the tag with the value.
Does someone know how to accomplish this?
If you have the option of converting this property to string instead of storing it as a DateTime object, you can set it to String.Empty instead of DateTime.MinValue. The serializer will then create an empty tag.
Again, as far as I know, this only works with strings.

Unhandled Exception: System.Xml.XPath.XPathException: Expression must evaluate t o a node-set

I am trying to select all nodes with attribute equal to something, I got the error in title.
My Xpath string looks like //#[id=****], anyone know what's wrong?
Your XPath expression probably should be:
//*[#id='something']
Which means match all elements whose id attributes are equal to something, anywhere in the document.
EDIT: If you want the id attribute nodes themselves and not their parent elements, you can use:
//*[#id='something']/#id
Or even better, as #Dimitre Novatchev suggested:
//#id[. = 'something']
I am trying to select all nodes with
attribute equal to something, I got
the error in title.
My Xpath string looks like
//#[id=****], anyone know what's
wrong?
A lot of issues with this expression:
.1. //#[some-condition] The predicate can only be applied to selected nodes, but //# doesn't select any node. # is an abbreviation for attribute:: and this is an unfinished node-test. It is missing the node-type or node-name here.
What would be correct is: //#*[some-condition] or //#attrName[some-condition]
.2. id=**** is syntactically invalid, unless ** is a valid XPath expression itself. My guess is that you want to get all attributes with value equal to some known, literal value. In any such case the syntax to use is id='someLiteral -- do note the single quotes (they can also be double quotes) surrounding the literal value.
Solution:
//*[#id='something']
This selects all elements in the XML document that have attribute id with value 'something'.
//#id[. = 'something']
This selects all attributes named id in the XML document, whose value is 'something'.
//#*[. = 'something']
This selects all attributes in the XML document (regardless of their name), whose value is 'something'.

Categories

Resources