XmlConvert.VerifyName(String) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
根據 W3C Extended Markup Language Recommendation,驗證確定名稱是有效的名稱。
public:
static System::String ^ VerifyName(System::String ^ name);
public static string VerifyName (string name);
static member VerifyName : string -> string
Public Shared Function VerifyName (name As String) As String
參數
- name
- String
要驗證的名稱。
傳回
名稱 (如果它是有效的 XML 名稱)。
例外狀況
name
不是有效的 XML 名稱。
name
是 null
或是 String.Empty。
範例
下列範例會 VerifyName
使用 方法來撰寫專案名稱。
#using <System.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::Xml;
int main()
{
XmlTextWriter^ writer = gcnew XmlTextWriter( "out.xml", nullptr );
String^ tag = "item name";
try
{
// Write the root element.
writer->WriteStartElement( "root" );
writer->WriteStartElement( XmlConvert::VerifyName( tag ) );
}
catch ( XmlException^ e )
{
Console::WriteLine( e->Message );
Console::WriteLine( "Convert to a valid name..." );
writer->WriteStartElement( XmlConvert::EncodeName( tag ) );
}
writer->WriteString( "hammer" );
writer->WriteEndElement();
// Write the end tag for the root element.
writer->WriteEndElement();
writer->Close();
}
using System;
using System.Xml;
public class Sample{
public static void Main(){
XmlTextWriter writer = new XmlTextWriter ("out.xml", null);
string tag = "item name";
try{
// Write the root element.
writer.WriteStartElement("root");
writer.WriteStartElement(XmlConvert.VerifyName(tag));
}
catch (XmlException e){
Console.WriteLine(e.Message);
Console.WriteLine("Convert to a valid name...");
writer.WriteStartElement(XmlConvert.EncodeName(tag));
}
writer.WriteString("hammer");
writer.WriteEndElement();
// Write the end tag for the root element.
writer.WriteEndElement();
writer.Close();
}
}
Imports System.Xml
Public Class Sample
Public Shared Sub Main()
Dim writer As New XmlTextWriter("out.xml", Nothing)
Dim tag As String = "item name"
Try
' Write the root element.
writer.WriteStartElement("root")
writer.WriteStartElement(XmlConvert.VerifyName(tag))
Catch e As XmlException
Console.WriteLine(e.Message)
Console.WriteLine("Convert to a valid name...")
writer.WriteStartElement(XmlConvert.EncodeName(tag))
End Try
writer.WriteString("hammer")
writer.WriteEndElement()
' Write the end tag for the root element.
writer.WriteEndElement()
writer.Close()
End Sub
End Class
備註
此方法可以透過下列方式與 類別搭配 XmlWriter 使用。
try{
writer.WriteStartElement(XmlConvert.VerifyName("item"),"bar");
}
catch(Exception e)
{
Console.WriteLine("error");
}