的XElement
值明確設置爲空的所有元素字符串應該工作。正如您從XElement.IsEmpty
的文檔中看到的,LINQ到XML已經將節點沒有內容(如new XElement("foo")
)視爲與長度爲零的節點(如new XElement("foo", string.Empty)
)不同。
但在不工作的情況下,或者如果你需要微調XML輸出的一些其他方面,你可以得到一個定製XmlWriter
:
public class MyWriter : XmlWriter
{
private readonly XmlWriter inner;
public MyWriter(XmlWriter inner)
{
this.inner = inner;
}
public void Dispose()
{
((IDisposable) inner).Dispose();
}
public override void WriteStartDocument()
{
inner.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
inner.WriteStartDocument(standalone);
}
public override void WriteEndDocument()
{
inner.WriteEndDocument();
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
inner.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
inner.WriteStartElement(prefix, localName, ns);
}
public override void WriteEndElement()
{
inner.WriteFullEndElement();
}
public override void WriteFullEndElement()
{
inner.WriteFullEndElement();
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
inner.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
inner.WriteEndAttribute();
}
public override void WriteCData(string text)
{
inner.WriteCData(text);
}
public override void WriteComment(string text)
{
inner.WriteComment(text);
}
public override void WriteProcessingInstruction(string name, string text)
{
inner.WriteProcessingInstruction(name, text);
}
public override void WriteEntityRef(string name)
{
inner.WriteEntityRef(name);
}
public override void WriteCharEntity(char ch)
{
inner.WriteCharEntity(ch);
}
public override void WriteWhitespace(string ws)
{
inner.WriteWhitespace(ws);
}
public override void WriteString(string text)
{
inner.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
inner.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteChars(char[] buffer, int index, int count)
{
inner.WriteChars(buffer, index, count);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
inner.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
inner.WriteRaw(data);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
inner.WriteBase64(buffer, index, count);
}
public override void Close()
{
inner.Close();
}
public override void Flush()
{
inner.Flush();
}
public override string LookupPrefix(string ns)
{
return inner.LookupPrefix(ns);
}
public override WriteState WriteState
{
get { return inner.WriteState; }
}
}
相關的方法是這樣的一種:
public override void WriteEndElement()
{
inner.WriteFullEndElement(); // always write both start and close tags
}
爲什麼這很重要? – 2011-06-15 08:51:25
@Dan軟件「吃」這可能是小錯誤,並沒有正確處理這個語法,我也一直處於這種情況。一般來說,這不重要。 – 2011-06-15 09:40:22