C# 實體集合和實體轉換成相應的string、XDocument、XElement、XDocument


https://msdn.microsoft.com/zh-cn/library/system.xml.linq.xelement(v=vs.110).aspx

 

XElement.Parse 方法 (String, LoadOptions)

.NET Framework (current version)
 
其他版本
 
 

負載 XElement 從包含 XML 字符串,可以選擇保留空白和保留行信息。

命名空間:    System.Xml.Linq
程序集:  System.Xml.Linq(位於 System.Xml.Linq.dll)

語法
 
 
 
public static XElement Parse(
	string text,
	LoadOptions options
)

參數

text
Type:  System.String

一個 String 包含 XML。

options
Type:  System.Xml.Linq.LoadOptions

一個 LoadOptions ,它指定空白行為以及是否加載基 URI 和行信息。

返回值

Type:  System.Xml.Linq.XElement

XElement 包含 XML 的字符串填充的。

備注
 
 

如果源 XML 有縮進,則將設置 PreserveWhitespace 中標記出來 options 導致讀取器讀取的源 XML 中的所有空白區域。 類型的節點 XText 創建同時有效空白和多余空白。

源 XML 有縮進,則不設置 PreserveWhitespace 中標記出來 options 導致讀取器會忽略所有源 XML 中無關緊要的空白區域。 不包括無關緊要的空白區域任何文本節點創建 XML 樹。

如果沒有源 XML 縮進,則將設置 PreserveWhitespace 中標記出來 options 不起作用。 仍保留有效空白,並且不有可能導致多個空白文本節點創建的無關緊要的空白區域的任何范圍。

有關詳細信息,請參閱 加載或分析 XML 時保留空白 和 序列化時保留空白

設置 SetBaseUri 不起作用時從其進行分析 String

XmlReader 可能有也可能沒有有效的行信息。 如果您設置 SetLineInfo, ,將報告的行信息從 XML 樹中設置行信息 XmlReader

如果您設置,則對性能產生負面影響 SetLineInfo 標志。

在加載 XML 文檔之后立即行信息是准確的。 如果在加載文檔之后修改 XML 樹,行信息可能會變得毫無意義。

LINQ to XML 的加載功能基於 XmlReader 因此,您可能會捕獲所引發的任何異常 XmlReader.Create 重載的方法和 XmlReader 方法來讀取和分析該文檔。

示例
 
 

下面的示例將字符串分析成 XElement 兩種不同方式︰ 保留空白區域和不保留空白區域。 然后使用查詢來確定生成的 XML 樹中的空白節點數。

C#
VB
 
                int whiteSpaceNodes;

XElement xmlTree1 = XElement.Parse("<Root> <Child> </Child> </Root>",
    LoadOptions.None);
whiteSpaceNodes = xmlTree1
    .DescendantNodesAndSelf()
    .OfType<XText>()
    .Where(tNode => tNode.ToString().Trim().Length == 0)
    .Count();
Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}",
    whiteSpaceNodes);

XElement xmlTree2 = XElement.Parse("<Root> <Child> </Child> </Root>",
    LoadOptions.PreserveWhitespace);
whiteSpaceNodes = xmlTree2
    .DescendantNodesAndSelf()
    .OfType<XText>()
    .Where(tNode => tNode.ToString().Trim().Length == 0)
    .Count();
Console.WriteLine("Count of white space nodes (preserving whitespace): {0}",
    whiteSpaceNodes);

該示例產生下面的輸出:

 
 
                Count of white space nodes (not preserving whitespace): 0
Count of white space nodes (preserving whitespace): 3

下面的示例保留行信息,因為它會分析該字符串。

C#
VB
 
                string markup =
@"<Root>
    <Child>
        <GrandChild/>
    </Child>
</Root>";

XElement xRoot = XElement.Parse(markup, LoadOptions.SetLineInfo);
Console.WriteLine("{0}{1}{2}",
    "Element Name".PadRight(20),
    "Line".PadRight(5),
    "Position");
Console.WriteLine("{0}{1}{2}",
    "------------".PadRight(20),
    "----".PadRight(5),
    "--------");
foreach (XElement e in xRoot.DescendantsAndSelf())
    Console.WriteLine("{0}{1}{2}",
        ("".PadRight(e.Ancestors().Count() * 2) + e.Name).PadRight(20),
        ((IXmlLineInfo)e).LineNumber.ToString().PadRight(5),
        ((IXmlLineInfo)e).LinePosition);

該示例產生下面的輸出:

 
 
                Element Name        Line Position
------------        ---- --------
Root                1    2
  Child             2    6
    GrandChild      3    10

 

實體集合和實體轉換成相應的string、XDocument、XElement、XDocument

 
一、前言

上篇隨筆主要是針對於Xml的特性Attribute與實體之間的匹配與轉換。該篇隨筆主要內容為將對象轉換成相應的Xml以及XElement。這2篇隨筆以不同的方式對Xml進行轉換與匹配,每種匹配都采用不同的角度進行操作。本文主要為對象實體的轉換,下篇側重於Xml的匹配。

 

二、Xml轉換

2.1 實體集合轉換Xml

實體集合轉換Xml的方法為:public static string ToXml<T>(IList<T> entities, string rootName = "") where T : new(),通過傳入的實體集合對象和Xml根名稱,可以轉換成相應的Xml,代碼如下:

復制代碼
 1         public static string ToXml<T>(IList<T> entities, string rootName = "") where T : new()
 2         {
 3             if (entities == null || entities.Count == 0)
 4             {
 5                 return string.Empty;
 6             }
 7 
 8             StringBuilder builder = new StringBuilder();
 9             builder.AppendLine(XmlResource.XmlHeader);
10 
11             XElement element = ToXElement<T>(entities, rootName);
12             builder.Append(element.ToString());
13 
14             return builder.ToString();
15         }
復制代碼

 針對於實體集合的轉換,轉換后的結果如下:

復制代碼
 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <MapperInfoSet>
 3   <MapperInfo>
 4     <Name>MapperInfoIndex0</Name>
 5     <CreatedTime>2012-02-19T08:54:44.9411601+08:00</CreatedTime>
 6     <IsActive>true</IsActive>
 7     <Value>0</Value>
 8     <Percent>50</Percent>
 9     <TargetUrl>www.codeplex.com?Id=0</TargetUrl>
10   </MapperInfo>
11   <MapperInfo>
12     <Name>MapperInfoIndex1</Name>
13     <CreatedTime>2012-02-19T08:54:44.9421602+08:00</CreatedTime>
14     <IsActive>false</IsActive>
15     <Value>1</Value>
16     <Percent>50</Percent>
17     <TargetUrl>www.codeplex.com?Id=1</TargetUrl>
18   </MapperInfo>
19 </MapperInfoSet>
復制代碼

 

2.2 實體轉換Xml

實體轉換Xml的方法為:public static string ToXml<T>(T entity) where T : new(),通過傳入的實體,可以轉換成相應的Xml,代碼如下:

復制代碼
 1         public static string ToXml<T>(T entity) where T : new()
 2         {
 3             if (entity == null)
 4             {
 5                 return string.Empty;
 6             }
 7 
 8             XElement element = ToXElement<T>(entity);
 9 
10             return element.ToString();
11         }
復制代碼

針對於單個實體的轉換,轉換后的結果如下:

復制代碼
1 <MapperInfo>
2   <Name>MapperInfoIndex0</Name>
3   <CreatedTime>2012-02-19T08:59:17.1387289+08:00</CreatedTime>
4   <IsActive>true</IsActive>
5   <Value>0</Value>
6   <Percent>50</Percent>
7   <TargetUrl>www.codeplex.com?Id=0</TargetUrl>
8 </MapperInfo>
復制代碼

 

2.3 實體集合轉換XElement

實體轉換XElement的方法為:public static XElement ToXElement<T>(IList<T> entities, string rootName = "") where T : new(),通過傳入的實體集合對象和Xml根名稱,可以轉換成相應的XElement,代碼如下:

復制代碼
 1         public static XElement ToXElement<T>(IList<T> entities, string rootName = "") where T : new()
 2         {
 3             if (entities == null || entities.Count == 0)
 4             {
 5                 return null;
 6             }
 7 
 8             if (string.IsNullOrWhiteSpace(rootName))
 9             {
10                 rootName = typeof(T).Name + XmlResource.XmlRootNameSuffix;
11             }
12 
13             XElement element = new XElement(rootName);
14 
15             foreach (T entity in entities)
16             {
17                 element.Add(ToXElement<T>(entity));
18             }
19 
20             return element;
21         }
復制代碼

 

2.4 實體集合轉換XmlDocument

實體轉換XmlDocument的方法為:public static XElement ToXmlDocument<T>(IList<T> entities, string rootName = "") where T : new(),通過傳入的實體集合對象和Xml根名稱,可以轉換成相應的XmlDocument,代碼如下:

復制代碼
 1         public static XmlDocument ToXmlDocument<T>(IList<T> entities, string rootName = "") where T : new()
 2         {
 3             if (entities == null || entities.Count == 0)
 4             {
 5                 return null;
 6             }
 7 
 8             XmlDocument xmlDocument = new XmlDocument();
 9             xmlDocument.LoadXml(ToXml<T>(entities, rootName));
10 
11             return xmlDocument;
12         }
復制代碼

 

2.5 實體轉換XElement

實體轉換XElement的方法為:public static string ToXElement<T>(T entity) where T : new(),通過傳入的實體,可以轉換成相應的XElement,代碼如下:

復制代碼
 1         public static XElement ToXElement<T>(T entity) where T : new()
 2         {
 3             if (entity == null)
 4             {
 5                 return null;
 6             }
 7 
 8             XElement element = new XElement(typeof(T).Name);
 9             PropertyInfo[] properties = typeof(T).GetProperties();
10             XElement innerElement = null;
11             object propertyValue = null;
12 
13             foreach (PropertyInfo property in properties)
14             {
15                 propertyValue = property.GetValue(entity, null);
16                 innerElement = new XElement(property.Name, propertyValue);
17                 element.Add(innerElement);
18             }
19 
20             return element;
21         }
復制代碼

 

2.6 實體集合轉換XDocument

實體轉換XDocument的方法為:public static XDocument ToXDocument<T>(IList<T> entities, string rootName = "") where T : new(),通過傳入的實體集合對象和Xml根名稱,可以轉換成相應的XDocument,代碼如下:

復制代碼
1         public static XDocument ToXDocument<T>(IList<T> entities, string rootName = "") where T : new()
2         {
3             if (entities == null || entities.Count == 0)
4             {
5                 return null;
6             }
7           
8             return  XDocument.Parse(ToXml<T>(entities, rootName));
9         }
復制代碼

 

三、總結

以上的代碼很少,主要通過重構來使代碼簡化。當然,將實體集合和實體轉換為相應的string、XDocument、XElement、XDocument是非常簡單的。單元測試的代碼就不貼了,占地方。下篇隨筆主要是如何將本文中轉換的Xml進行匹配,本文所有的代碼如下:


復制代碼
public class SimpleXmlConverter
{
public static string ToXml<T>(IList<T> entities, string rootName = "") where T : new()
{
if (entities == null || entities.Count == 0)
{
return string.Empty;
}

StringBuilder builder = new StringBuilder();
builder.AppendLine(XmlResource.XmlHeader);

XElement element = ToXElement<T>(entities, rootName);
builder.Append(element.ToString());

return builder.ToString();
}

public static XmlDocument ToXmlDocument<T>(IList<T> entities, string rootName = "") where T : new()
{
if (entities == null || entities.Count == 0)
{
return null;
}

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(ToXml<T>(entities, rootName));

return xmlDocument;
}

public static XDocument ToXDocument<T>(IList<T> entities, string rootName = "") where T : new()
{
if (entities == null || entities.Count == 0)
{
return null;
}

return XDocument.Parse(ToXml<T>(entities, rootName));
}

public static XElement ToXElement<T>(IList<T> entities, string rootName = "") where T : new()
{
if (entities == null || entities.Count == 0)
{
return null;
}

if (string.IsNullOrWhiteSpace(rootName))
{
rootName = typeof(T).Name + XmlResource.XmlRootNameSuffix;
}

XElement element = new XElement(rootName);

foreach (T entity in entities)
{
element.Add(ToXElement<T>(entity));
}

return element;
}

public static string ToXml<T>(T entity) where T : new()
{
if (entity == null)
{
return string.Empty;
}

XElement element = ToXElement<T>(entity);

return element.ToString();
}

public static XElement ToXElement<T>(T entity) where T : new()
{
if (entity == null)
{
return null;
}

XElement element = new XElement(typeof(T).Name);
PropertyInfo[] properties = typeof(T).GetProperties();
XElement innerElement = null;
object propertyValue = null;

foreach (PropertyInfo property in properties)
{
propertyValue = property.GetValue(entity, null);
innerElement = new XElement(property.Name, propertyValue);
element.Add(innerElement);
}

return element;
}

public static XElement ToXElement(Type type)
{
if (type == null)
{
return null;
}

XElement element = new XElement(type.Name);
PropertyInfo[] properties = type.GetProperties();
XElement innerElement = null;

foreach (PropertyInfo property in properties)
{
innerElement = new XElement(property.Name, null);
element.Add(innerElement);
}

return element;
}
}
復制代碼

 
 
 
« 上一篇: XmlAttribute與實體的轉換和匹配方案(附源碼)
» 下一篇: Xml匹配為對象集合(兩種不同的方式)
posted @  2012-02-19 09:46 jasen.kin 閱讀(4346) 評論(4) 編輯 收藏

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM