CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 167

167

Chương 5: XML

if (textContent != null) {

XmlNode content;

content = parent.OwnerDocument.CreateTextNode(textContent);

node.AppendChild(content);

}

return node;

}

public static XmlNode AddAttribute(string attributeName,

string textContent, XmlNode parent) {

XmlAttribute attribute;

attribute = parent.OwnerDocument.CreateAttribute(attributeName);

attribute.Value = textContent;

parent.Attributes.Append(attribute);

return attribute;

}

}

Bây giờ bạn có thể viết mã lệnh để tạo một tài liệu XML (giống mục 5.2) với cú pháp đơn giản
hơn như sau:

public class GenerateXml {

private static void Main() {

// Tạo tài liệu.

XmlDocument doc = new XmlDocument();

XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

doc.AppendChild(docNode);

XmlNode products = doc.CreateElement("products");

doc.AppendChild(products);

// Thêm hai product.

XmlNode product = XmlHelper.AddElement("product", null,

products);

XmlHelper.AddAttribute("id", "1001", product);

XmlHelper.AddElement("productName", "Gourmet Coffee", product);

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.