c set xml content not to wrap and property xsi:nil=true empty node add

  • 2020-05-27 04:42:20
  • OfStack

1. Set the content format of xml to be non-newline
The default code to create and generate xml is as follows:
 
XmlDocument doc = new XmlDocument(); 
// This is omitted for code such as creating nodes .... 
// save  
doc.Save(filename); 
 The node generated by the result has a newline:  
<UserName> 
</UserName> 

This will result in the failure of any validation in xsd. To avoid newline feed, doc.Save (filename); Can be changed to:
 
using (XmlTextWriter xtw = new XmlTextWriter(filename, null)) 
{ 
//None Means that no special format should be applied 1 The opposite enumeration values Indented Said the indentation  
xtw.Formatting = Formatting.None; 
doc.Save(xtw); 
} 

2. Add an empty node with the property xsi:nil="true"
 
public static XmlElement CreateNodeWithNullAttr(XmlDocument doc, string nodeName) 
{ 
XmlElement element = doc.CreateElement(nodeName); 
XmlAttribute attr = doc.CreateAttribute("xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance"); 
attr.Value = "true"; 
element.SetAttributeNode(attr); 
//element.Attributes.Append(attr); 
return element; 
} 

Related articles: